/*
 Copyright (c) 2012-2018 Open Lab
 Written by Roberto Bicchierai and Silvia Chelazzi http://roberto.open-lab.com
 Permission is hereby granted, free of charge, to any person obtaining
 a copy of this software and associated documentation files (the
 "Software"), to deal in the Software without restriction, including
 without limitation the rights to use, copy, modify, merge, publish,
 distribute, sublicense, and/or sell copies of the Software, and to
 permit persons to whom the Software is furnished to do so, subject to
 the following conditions:

 The above copyright notice and this permission notice shall be
 included in all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
var isRowClick = true;
function GridEditor(master) {
  this.master = master; // is the a GantEditor instance

  var editorTabel = $.JST.createFromTemplate({}, "TASKSEDITHEAD");
  if (!master.permissions.canSeeDep)
    editorTabel.find(".requireCanSeeDep").hide();

  this.gridified = $.gridify(editorTabel);
  this.element = this.gridified.find(".gdfTable").eq(1);

  this.minAllowedDate=new Date(new Date().getTime()-3600000*24*365*20).format();
  this.maxAllowedDate=new Date(new Date().getTime()+3600000*24*365*30).format();
}


GridEditor.prototype.fillEmptyLines = function () {
  //console.debug("fillEmptyLines")
  var factory = new TaskFactory();
  var master = this.master;

  //console.debug("GridEditor.fillEmptyLines");
  var rowsToAdd = master.minRowsInEditor - this.element.find(".taskEditRow").length;
  var empty=this.element.find(".emptyRow").length;
  rowsToAdd=Math.max(rowsToAdd,empty>5?0:5-empty);

  //fill with empty lines
  for (var i = 0; i < rowsToAdd; i++) {
    var emptyRow = $.JST.createFromTemplate({}, "TASKEMPTYROW");
    if (!master.permissions.canSeeDep)
      emptyRow.find(".requireCanSeeDep").hide();

    //click on empty row create a task and fill above
    emptyRow.click(function (ev) {
      //console.debug("emptyRow.click")
      var emptyRow = $(this);
      //add on the first empty row only
      if (!master.permissions.canAdd || emptyRow.prevAll(".emptyRow").length > 0)
        return;

      master.beginTransaction();
      var lastTask;
      var start = new Date().getTime();
      var level = 0;
      if (master.tasks[0]) {
        start = master.tasks[0].start;
        level = master.tasks[0].level + 1;
      }

      //fill all empty previouses
      var cnt=0;
      emptyRow.prevAll(".emptyRow").addBack().each(function () {
        cnt++;
        var ch = factory.build("tmp_fk" + new Date().getTime()+"_"+cnt, defaultTaskName+""+newId, "", level, start, Date.workingPeriodResolution);
        var task = master.addTask(ch);
        lastTask = ch;
		newId++;
      });
      master.endTransaction();
      if (lastTask.rowElement) {
        lastTask.rowElement.find("[name=name]").focus();//focus to "name" input
      }
    });
    this.element.append(emptyRow);
  }
};


GridEditor.prototype.addTask = function (task, row, hideIfParentCollapsed) {
  //console.debug("GridEditor.addTask",task,row);
  //var prof = new Profiler("ganttGridEditor.addTask");

  //remove extisting row
  //this.element.find("#tid_" + task.id).remove();
	$("#tid_" + task.id).remove();

  if(task.id.indexOf("tmp")>=0){
	 var parents;
	  var futureParents = task.getParents();
		if (futureParents.length > 0){
			for ( var i = 0; i < futureParents.length; i++) {
				if(parents){
					if(futureParents[i].level>parents){
						parents=futureParents[i];
					}
				}else{
					parents=futureParents[i];
				}
			}
		}
		if(parents && task.getParent().isLoop == "0"){
			if(task.end&&task.end==""){
				task.end=parents.end;
			}
			if(task.start&&task.start==""){
				task.start=parents.start;
			}
			if(task.principal&&task.principal==""){
				task.principal=parents.principal;
			}
			if(parents.approver&&parents.approver!=""){
				task.approver=parents.approver;
			}else{
				task.approver=this.master.gantt.master.pmId;
			}
			if(task.duration&&task.duration==""){
				task.duration=recomputeDuration(parents.start, parents.end);
			}
		}
	
  }
  
  var taskRow = $.JST.createFromTemplate(task, "TASKROW");

  if (!this.master.permissions.canSeeDep)
    taskRow.find(".requireCanSeeDep").hide();

  if (!this.master.permissions.canSeePopEdit)
    taskRow.find(".edit .teamworkIcon").hide();

  //save row element on task
  task.rowElement = taskRow;

  this.bindRowEvents(task, taskRow);

  if (typeof(row) != "number") {
    var emptyRow = this.element.find(".emptyRow:first"); //tries to fill an empty row
    if (emptyRow.length > 0){
    	emptyRow.replaceWith(taskRow);
    }else{
      this.element.append(taskRow);
    }
  } else {
    var tr = this.element.find("tr.taskEditRow").eq(row);
    if (tr.length > 0) {
      tr.before(taskRow);
    } else {
      this.element.append(taskRow);
    }

  }

  //[expand]
  if (hideIfParentCollapsed) {
    if (task.collapsed) taskRow.addClass('collapsed');
    var collapsedDescendant = this.master.getCollapsedDescendant();
    if (collapsedDescendant.indexOf(task) >= 0) taskRow.hide();
  }
  //prof.stop();
  return taskRow;
};

GridEditor.prototype.refreshExpandStatus = function (task) {
  //console.debug("refreshExpandStatus",task);
  if (!task) return;
  if (task.isParent()) {
    task.rowElement.addClass("isParent");
  } else {
    task.rowElement.removeClass("isParent");
  }


  var par = task.getParent();
  if (par && !par.rowElement.is("isParent")) {
    par.rowElement.addClass("isParent");
  }

};

GridEditor.prototype.refreshTaskRow = function (task,falg) {
  //console.debug("refreshTaskRow")
  //var profiler = new Profiler("editorRefreshTaskRow");

  var canWrite= task.canWrite;

  var row = task.rowElement;
//console.log("refreshRow: "+task.getRow());
  row.find(".taskRowIndex").html(task.getRow() + 1);
  row.find(".indentCell").css("padding-left", task.level * 10 + 18);
  row.find("[name=name]").val(task.name);
  row.find("[name=code]").val(task.code);
  row.find("[status]").attr("status", task.status);
  row.find("[rtype]").attr("rtype", task.reportType);

  //row.find("[name=duration]").val(durationToString(task.duration)).prop("readonly",!canWrite || task.isParent() && task.master.shrinkParent);
  row.find("[name=duration]").val(durationToString(task.duration)).prop("readonly",true);
  //row.find("[name=progress]").val(task.progress+'%').prop("readonly",!canWrite || task.progressByWorklog==true);
  row.find("[name=progress]").val(task.progress+'%').prop("readonly",true);
  row.find("[name=startIsMilestone]").prop("checked", task.startIsMilestone);
  row.find("[name=start]").val(new Date(task.start).format()).updateOldValue().prop("readonly",!canWrite || task.depends || !task.canWrite || task.isParent()); // called on dates only because for other field is called on focus event
  row.find("[name=endIsMilestone]").prop("checked", task.endIsMilestone);
  row.find("[name=end]").val(new Date(task.end).format()).prop("readonly",!canWrite || task.isParent() && task.master.shrinkParent).updateOldValue();
  
  row.find("[name=realstart]").val(((!(task.realstart))||task.realstart<0)?"":new Date(task.realstart).format()).updateOldValue().prop("readonly", true ); // called on dates only because for other field is called on focus event
  row.find("[name=realend]").val(((!(task.realend))||task.realend<0)?"":new Date(task.realend).format()).updateOldValue().prop("readonly", true ); // called on dates only because for other field is called on focus event
  //row.find("[name=realstart]").val(((!(task.realstart))||task.realstart<0)?new Date(task.start).format():new Date(task.realstart).format()).updateOldValue().prop("readonly", true );
  //row.find("[name=realend]").val(((!(task.realend))||task.realend<0)?new Date(task.end).format():new Date(task.realend).format()).updateOldValue().prop("readonly", true ); // called on dates only because for other field is called on focus event
  
  row.find("[name=planWorkload]").val((task.planWorkload<0)?"":task.planWorkload).updateOldValue().prop("readonly", true ); // called on dates only because for other field is called on focus event
  row.find("[name=realWorkload]").val((task.realWorkload<0)?"":task.realWorkload).updateOldValue().prop("readonly", true ); // called on dates only because for other field is called on focus event


  row.find("[name=typeId]").val(task.typeId).prop("disabled",!canWrite || task.isParent() && task.master.shrinkParent).updateOldValue();
  row.find("[name=principal]").val(task.principal).prop("disabled",!canWrite || task.isParent() && task.master.shrinkParent).updateOldValue();
  row.find("[name=approver]").val(task.approver).prop("disabled",!canWrite || task.isParent() && task.master.shrinkParent).updateOldValue();
  row.find("[name=isMilestone]").val(task.isMilestone).prop("disabled",!canWrite || task.isParent() && task.master.shrinkParent).updateOldValue();
  row.find("[name=isPhase]").val(task.isPhase).prop("disabled",!canWrite || task.isParent() && task.master.shrinkParent).updateOldValue();

  row.find("[name=typeId]").val(task.typeId).prop("disabled",!canWrite || task.isParent() && task.master.shrinkParent).updateOldValue();
  
  if(canWrite&&task.coordinateEdit&&task.lockedEmpId&&task.lockedEmpId!=""&&task.lockedEmpId!="-1"){
	  row.find("[name=typeId]").val(task.typeId).prop("disabled",true).updateOldValue();
	  row.find("[name=principal]").val(task.principal).prop("disabled",true).updateOldValue();
	  console.dir("task.lockedEmpId");
  }

  row.find(".releaseStatus").attr("isDisabled",task.id=='tmp_-1'||!canWrite || task.isParent() && task.master.shrinkParent);//选中发布
  
  
  row.find("[name=depends]").val(task.depends);
  
  //任务类型
  if(task.type){
	  getSelectTasks(row,task);
  }else{
	  row.find(".taskType").html(task.type);
  }
  //任务审批人
  if(task.getApprover()){
	  getSelectApprovers(row,task);
  }else if(task.id!='tmp_-1'){
	  getSelectApprovers(row,task);  
  }else{
	  row.find(".approverText").html(task.getApprover());
  }
  //任务负责人
  if(task.getPrincipal()){
	  getSelectPrincipals(row,task);
  }else if(task.id!='tmp_-1'){
	  getSelectPrincipals(row,task);
  }else{
	  row.find(".principalText").html(task.getPrincipal());//任务审批人
  }
  
  
  
  row.find(".descriptionText").html(task.getDescription());//任务审批人
  row.find(".coordinateEdit").html(task.coordinateEdit?"是":"否");
  //row.find(".isMilestone").html(task.isMilestone?"是":"否");//里程碑
  var isMilestoneEl = row.find("[name=isMilestone]");
  row.find("[name=isMilestone] option").remove();
  getSelectIsTrue(isMilestoneEl,task.isMilestone, task);
  
  //row.find(".isPhase").html(task.isPhase?"是":"否");
  var isPhaseEl = row.find("[name=isPhase]");
  row.find("[name=isPhase] option").remove();
  getSelectIsTrue(isPhaseEl,task.isPhase, task);
  
  row.find(".taskAssigs").html(task.getAssigsString());

  //manage collapsed
  if (task.collapsed)
    row.addClass("collapsed");
  else
    row.removeClass("collapsed");

  if(task.getChildren().length>0&&!(task.isProjectRoot)){
	  row.find("[name=progress]").val("");
	  var rs = task.getRealBoudaries().realstart;
	  var re = task.getRealBoudaries().realend;
	  row.find("[name=realstart]").val(((!(rs))||rs<0||rs==Infinity)?"":new Date(rs).format()).updateOldValue().prop("readonly", true ); // called on dates only because for other field is called on focus event
	  row.find("[name=realend]").val(((!(re))||re<0)?"":new Date(re).format()).updateOldValue().prop("readonly", true ); // called on dates only because for other field is called on focus event

  }
  if(task.getChildren().length<=0 && !(task.isProjectRoot)){
	  var endDate = new Date(task.end);
	  var nowDate = new Date();
	  if(!falg){
		  row.find("#add_"+task.id).hide();
		  if(nowDate > endDate && task.status=='STATUS_ACTIVE'){
			  row.find("#add_"+task.id).attr("isDelay","false");
		  }
	  }else{
		  if(nowDate > endDate && task.status=='STATUS_ACTIVE'){
			  row.find("#add_"+task.id).show();
			  row.find("#add_"+task.id).attr("isDelay","false");
		  }else {
			  row.find("#add_"+task.id).hide();
		  }
	  }
	  row.find("#taskStatus_"+task.id).empty();
	  var taskStatusValue = task.taskStatusValue;
	  if("0" == taskStatusValue){
		  row.find("#taskStatus_"+task.id).append("进行中");
	  }else if("1" == taskStatusValue){
		  row.find("#taskStatus_"+task.id).append("待审");
	  }else if("2" == taskStatusValue){
		  row.find("#taskStatus_"+task.id).append("未完成");
	  }
	  else if("3" == taskStatusValue){
		  row.find("#taskStatus_"+task.id).append("完成");
	  }
	  else if("4" == taskStatusValue){
		  row.find("#taskStatus_"+task.id).append("取消");
	  }
	  else if("5" == taskStatusValue){
		  row.find("#taskStatus_"+task.id).append("新建");
	  }
  }
  if(task.isProjectRoot){
	  row.find("[name=progress]").val("").prop("readonly", true );
	  row.find("[name=realstart]").val("").updateOldValue().prop("readonly", true ); // called on dates only because for other field is called on focus event
	  row.find("[name=realend]").val("").updateOldValue().prop("readonly", true ); // called on dates only because for other field is called on focus event
	  //row.find("[name=duration]").val("").prop("readonly",!canWrite || task.isParent() && task.master.shrinkParent);
	  row.find("[name=duration]").val("").prop("readonly",true);
	  row.find(".coordinateEdit").html("");
	  row.find(".isMilestone").html("");
	  row.find(".isPhase").html("");
  }
  task.needRefreshSelect = false;
  //Enhancing the function to perform own operations
  this.master.element.trigger('gantt.task.afterupdate.event', task);
  //profiler.stop();
};
function getNowDate(s){
	var date = s;
	var year = date.getFullYear();
	var month =  date.getMonth();
	var day =  date.getDate();
	return year+"-"+month+"-"+day;
}
function getSelectTasks(row,task){
	 var typeEl = row.find("[name=typeId]");
	 row.find("[name=typeId] option").remove();
	  for(var i=0; i< task.master.types.length;i++){
		  var types = task.master.types[i];
		  var  typeOpt = $("<option>");
		  typeOpt.val(types.id).html(types.name);
		  if(task.typeId == types.id){
			  typeOpt.attr("selected", "true");
		  }
		  	typeEl.append(typeOpt);
	  }
}

function getSelectApprovers(row,task){
	//if(!task.needRefreshSelect)
	//  return;
	 var approverEl = row.find("[name=approver]");
	 row.find("[name=approver] option").remove();
	  var approverOpt = $("<option>");
	  	approverOpt.val("").html("");
	  approverEl.append(approverOpt);
	  if(task.typeId =="Q"){
		  for(var i=0; i< task.master.qaResources.length;i++){
			  var res = task.master.qaResources[i];
			  approverOpt = $("<option>");
			  approverOpt.val(res.id).html(res.name);
			  if(task.approver == res.id)
				  approverOpt.attr("selected", "true");
			  approverEl.append(approverOpt);
		  }
	  }else{
		  for(var i=0; i< task.master.resources.length;i++){
			  var res = task.master.resources[i];
			  approverOpt = $("<option>");
			  approverOpt.val(res.id).html(res.name);
			  if(task.approver == res.id)
				  approverOpt.attr("selected", "true");
			  approverEl.append(approverOpt);
		  }
	  }
	
}

function getSelectPrincipals(row,task){
	//if(!task.needRefreshSelect)
	//  return;
	var principalEl = row.find("[name=principal]");
	row.find("[name=principal] option").remove();
	 var principalElOpt = $("<option>");
	 principalElOpt.val("").html("");
	 principalEl.append(principalElOpt);
	  if(task.typeId =="Q"){
		  //for(var i=0; i< task.master.qaOnlyResources.length;i++){
			for(var i=0; i< task.master.qaResources.length;i++){
			  var res = task.master.qaResources[i];
			  principalElOpt = $("<option>");
			  principalElOpt.val(res.id).html(res.name);
			  if(task.principal == res.id){
				  principalElOpt.attr("selected", "true");
			  }
			  principalEl.append(principalElOpt);
		  }
	  }else{
		  
		  for(var i=0; i< task.master.resources.length;i++){
			  var res = task.master.resources[i];
			  principalElOpt = $("<option>");
			  principalElOpt.val(res.id).html(res.name);
			  if(task.principal == res.id)
				  principalElOpt.attr("selected", "true");
			  principalEl.append(principalElOpt);
		  }
	  }
}

function getSelectIsTrue(el,falg,task){
	//if(!task.needRefreshSelect)
	 // return;
	  if(falg){
		  var principalElOpt = $("<option>");
		  principalElOpt.val(true).html("是");
		  principalElOpt.attr("selected", "true");
		  el.append(principalElOpt);
		  el.append($("<option>").val(false).html("否"));
	  }else{
		  var principalElOpt = $("<option>");
		  principalElOpt.val(true).html("是");
		  el.append(principalElOpt);
		  el.append($("<option>").val(false).html("否").attr("selected", "true"));
	  }
}


GridEditor.prototype.redraw = function () {
  //console.debug("GridEditor.prototype.redraw")
  //var prof = new Profiler("gantt.GridEditor.redraw");
  var falg=initDelaySwitch();
  for (var i = 0; i < this.master.tasks.length; i++) {
    this.refreshTaskRow(this.master.tasks[i],falg);
  }
  // check if new empty rows are needed
  if (this.master.fillWithEmptyLines)
    this.fillEmptyLines();

  //prof.stop()

};

GridEditor.prototype.reset = function () {
  this.element.find("[taskid]").remove();
};


GridEditor.prototype.bindRowEvents = function (task, taskRow) {
  var self = this;
  //console.debug("bindRowEvents",this,this.master,this.master.permissions.canWrite, task.canWrite);

  //bind row selection
  taskRow.click(function (event) {
    var row = $(this);
    //console.debug("taskRow.click",row.attr("taskid"),event.target)
    //var isSel = row.hasClass("rowSelected");
    row.closest("table").find(".rowSelected").removeClass("rowSelected");
    row.addClass("rowSelected");

    //set current task
    self.master.currentTask = self.master.getTask(row.attr("taskId"));

    //move highlighter
    self.master.gantt.synchHighlight();

    //if offscreen scroll to element
    var top = row.position().top;
    if (top > self.element.parent().height()) {
      row.offsetParent().scrollTop(top - self.element.parent().height() + 100);
    } else if (top <= 40) {
      row.offsetParent().scrollTop(row.offsetParent().scrollTop() - 40 + top);
    }
  });
   
  if (task.canWrite) {
	  self.bindRowInputEvents(task, taskRow);//绑定任务的事件
  } else { //cannot write: disable input
    taskRow.find("input").prop("readonly", true);
    taskRow.find("input:checkbox,select").prop("disabled", true);
    //增加查看计划点击事件
    taskRow.find(".reportStatus").click(function () {
		  var el = $(this);
		  var tr = el.closest("[taskid]");
		  var taskId = tr.attr("taskid");
		  var task = self.master.getTask(taskId);
		  selfMaster= self.master;
		    if(task.reportType=="T"){
		    	var testReports = self.master.testReports;
		    	var testReport;
		    	for (var int = 0; int < testReports.length; int++) {
					if(testReports[int].testReportId ==  task.qualityReportId){
						testReport = testReports[int];
					}
				}
		    	//新增
		    	if(testReport){
			    	 if(testReport.testReportId&&testReport.testReportId>0){
			    		 openNewWindow("/pm/processTestPlan.do?method=show&inGant=true&taskId="+taskId+"&projectId="+self.master.projectId
				    			 +"&testReportId="+testReport.testReportId
				    			 +"&securityLevel="+testReport.securityLevel
				    			 +"&reportTitle="+encodeURI(encodeURI(testReport.reportTitle))
				    			 +"&testProjectId="+testReport.testProjectId
				    			 +"&token="+escape(new Date()),'RWindow',0.6,0.7);
			    	 }
		    	}else{
		    		alert("权限不足,无法创建测试计划!");
		    	}
		    }else   if(task.reportType=="R"){
		    	if(taskId.indexOf("tmp")>=0){
		    		alert("已添加新任务，请先保存甘特图");
		    	}else if(task.master.__undoStack.length >0){
		    		alert("已修改任务，请先保存甘特图");
		    	}else{
		    		var qualityReportId = task.qualityReportId;
		    		if(qualityReportId&&qualityReportId>0){
	  				openNewWindow("/pm/reviewPlan.do?method=showGant&inGant=true&inGant=true&taskId="+taskId+"&reportId="+qualityReportId+"&token="+escape(new Date()),'RWindow',0.6,0.7);
		    		}else{
		    			alert("权限不足,无法创建评审计划!");
		    		}
		    	}
		    }else   if(task.reportType=="Q"){
		    	if(taskId.indexOf("tmp")>=0){
		    		alert("已添加新任务，请先保存甘特图");
		    	}else if(task.master.__undoStack.length >0){
		    		alert("已修改任务，请先保存甘特图");
		    	}else{
		    		var qualityReportId = task.qualityReportId;
		    		if(qualityReportId&&qualityReportId>0){
	  				openWindow("/pm/processAuditPlan.do?method=showGantt&inGant=true&taskId="+taskId+"&reportId="+qualityReportId+"&projectId="+self.master.projectId+"&token="+escape(new Date()),"QWindow");
		    		}else{
		    			alert("权限不足,无法创建审核计划!");
		    		}
		    	}
		    }
	  });
  }


  if (!this.master.permissions.canSeeDep)
    taskRow.find("[name=depends]").attr("readonly", true);

  self.bindRowExpandEvents(task, taskRow);//绑定任务的事件

  if (this.master.permissions.canSeePopEdit) {
    taskRow.find(".edit").click(function () {self.openFullEditor(task, false)});
    taskRow.dblclick(function (ev) { //open editor only if no text has been selected
      //if (window.getSelection().toString().trim()=="")
        self.openFullEditor(task, $(ev.target).closest(".taskAssigs").size()>0)
      });
  }
  //prof.stop();
};

var selfMaster;//设置全局
GridEditor.prototype.bindRowExpandEvents = function (task, taskRow) {
  var self = this;
  //expand collapse
  taskRow.find(".exp-controller").click(function () {
    var el = $(this);
    var taskId = el.closest("[taskid]").attr("taskid");
    var task = self.master.getTask(taskId);
    if (task.collapsed) {
      self.master.expand(task,false);
    } else {
      self.master.collapse(task,false);
    }
  });
  
  taskRow.find(".exp-iconfont").click(function () {
	    var el = $(this);
	    var taskId = el.closest("[taskid]").attr("taskid");
	    var task = self.master.getTask(taskId);
	    if (task.collapsed) {
	      self.master.expand(task,false);
	    } else {
	      self.master.collapse(task,false);
	    }
	  });
  
  	//批量发布状态
	taskRow.find(".releaseStatus").click(function () {
	  var el = $(this);
	  var row = el.closest("tr");
	  var taskId = row.attr("taskId");
	  var task = self.master.getTask(taskId);
	  	//增加批量发布任务项
	    batchReleaseTask(task,el,self);
	});
};

GridEditor.prototype.bindRowInputEvents = function (task, taskRow) {
  var self = this;
  //console.dir("=============bindRowInputEvents==========================");
  if(isRowClick==true){//如果行可编辑才设置为可编辑,这里影响前后置绘图，不能屏蔽啊
	  //bind dateField on dates
	  taskRow.find(".date").each(function () {
		 // console.dir("=============.date==========================");
	    var el = $(this);
	    el.click(function () {
	      var inp = $(this);
	      inp.dateField({
	        inputField: el,
	        minDate:self.minAllowedDate,
	        maxDate:self.maxAllowedDate,
	        callback:   function (d) {
	          $(this).blur();
	        }
	      });
	    });
	    
	    el.blur(function (date) {
	      var inp = $(this);
		    var row = inp.closest("tr");
		    var taskId = row.attr("taskId");
		    var taskt = self.master.getTask(taskId);
		    var parents=getTaskDateChangeValue(taskt);
			var falg=true;
			if(parents){
				if (parents.start > Date.parseString(row.find("[name=start]").val()).getTime()) {
					if(self.master.gantt.master.pmId!=self.master.gantt.master.currentEmpId&&task.isLocked){
						alert("计划开始时间早于项目开始日期，不能调整");
						falg = false;
					}else if(self.master.gantt.master.pmId==self.master.gantt.master.currentEmpId){
						falg=confirm("计划开始时间早于项目开始日期，是否修改项目的开始日期为【"+Date.parseString(row.find("[name=start]").val()).format()+"】？");
					}
				}
				if (parents.end < Date.parseString(row.find("[name=end]").val()).getTime()) {
					if(self.master.gantt.master.pmId!=self.master.gantt.master.currentEmpId&&task.isLocked){
						alert("计划结束时间晚于项目结束日期，不能调整");
						falg = false;
					}else if(self.master.gantt.master.pmId==self.master.gantt.master.currentEmpId){
						falg=confirm("计划结束时间晚于项目结束日期，是否修改项目的结束日期为【"+Date.parseString(row.find("[name=end]").val()).format()+"】？");
					}
				}
			}

			if(falg){
			      if (inp.isValueChanged()) {
			        if (!Date.isValid(inp.val())) {
			          alert(GanttMaster.messages["INVALID_DATE_FORMAT"]);
			          inp.val(inp.getOldValue());
			
			        } else {
			          var row = inp.closest("tr");
			          var taskId = row.attr("taskId");
			          var task = self.master.getTask(taskId);
			
			          var leavingField = inp.prop("name");
			          var dates = resynchDates(inp, row.find("[name=start]"), row.find("[name=startIsMilestone]"), row.find("[name=duration]"), row.find("[name=end]"), row.find("[name=endIsMilestone]"));
			          //console.debug("resynchDates",new Date(dates.start), new Date(dates.end),dates.duration)
			          //update task from editor
			          self.master.beginTransaction();
			          self.master.changeTaskDates(task, dates.start, dates.end);
			          self.master.endTransaction();
			          inp.updateOldValue(); //in order to avoid multiple call if nothing changed
			        }
			      }
			}else{
				inp.val(inp.getOldValue());
				return false;
			}
	      
	      
	    });
	  });
	
	
	  //milestones checkbox
	  taskRow.find(":checkbox").click(function () {
		  //console.dir("=============.checkbox==========================");

	    var el = $(this);
	    var row = el.closest("tr");
	    var taskId = row.attr("taskId");
	
	    var task = self.master.getTask(taskId);
	
	    //update task from editor
	    var field = el.prop("name");
	
	    if (field == "startIsMilestone" || field == "endIsMilestone") {
	      self.master.beginTransaction();
	      //milestones
	      task[field] = el.prop("checked");
	      resynchDates(el, row.find("[name=start]"), row.find("[name=startIsMilestone]"), row.find("[name=duration]"), row.find("[name=end]"), row.find("[name=endIsMilestone]"));
	      self.master.endTransaction();
	    }
	    
	  });
	  
	  //milestones select
	  taskRow.find("select").click(function () {
		  //console.dir("=============.select==========================");
		  var selectel = $(this);
		  var row = selectel.closest("tr");
		  var taskId = row.attr("taskId");
		  
		  var task = self.master.getTask(taskId);
		  
		/*  if (field == "type") {
			  if(el.isValueChanged()){
				  self.master.beginTransaction();
				  //milestones
				  task[field] = el.prop("checked");
				  resynchDates(el, row.find("[name=start]"), row.find("[name=startIsMilestone]"), row.find("[name=duration]"), row.find("[name=end]"), row.find("[name=endIsMilestone]"));
				  self.master.endTransaction();
			  }
		  }*/
		  
	  });
	  
	
	  taskRow.find("select").focus(function () {
		  //console.dir("=============select1q2==========================");
		  $(this).updateOldValue();
	
	  }).blur(function (event) {
		  var el = $(this);
		    var row = el.closest("tr");
		    var taskId = row.attr("taskId");
		    var task = self.master.getTask(taskId);
		    //update task from editor
		    var field = el.prop("name");
		    
		    if (el.isValueChanged()) {
		    	if(field=='typeId'){
			    		//!confirm(alertMsg)
			    		//a)	当前任务已填写任务报告，修改时给出提示：任务已经填过任务报告，修改任务类型会去除不符合限制的任务成员，并将其任务报告删除！
			    		//b)	当前任务是QA活动、评审活动、测试活动且已填写质量报告，评审报告、测试报告时，切换成其他活动类型，修改时给出提示：任务已经填过质量报告, 修改任务类型将取消与质量报告、相关质量数据的关联！
		    		var qualityReportId = task.qualityReportId;
			    	if((el.getOldValue()=="Q"||el.getOldValue()=="T"||el.getOldValue()=="R")&&el.val()!="Q"&&el.val()!="T"&&el.val()!="R"&&qualityReportId&&qualityReportId!=""){
			    		if(!confirm("任务已经填过质量报告, 修改任务类型将取消与质量报告、相关质量数据的关联！")){
			    			el.val(el.getOldValue());
			    		}else{
			    			 self.master.beginTransaction();
			    			 task[field] = el.val();
			    		     task.reportType = "";
			    		     task.qualityReportId = "";
			    			 self.master.endTransaction();
			    			// self.editor.refreshExpandStatus(task);
			    		}
			    	}else if((el.getOldValue()=="Q"||el.getOldValue()=="T"||el.getOldValue()=="R")&&(el.val()=="Q"||el.val()=="T"||el.val()=="R")&&qualityReportId&&qualityReportId!=""){
						 if(!confirm("任务已经填过质量报告, 修改任务类型将取消与质量报告、相关质量数据的关联！")){
				  			el.val(el.getOldValue());
				  		}else{
				  			 self.master.beginTransaction();
				  			 task[field] = el.val();
				  		     task.reportType =el.val();
				  		     task.qualityReportId = "";
				  			 self.master.endTransaction();
				  			 //self.editor.refreshExpandStatus(task);
				  		}
			    	}else if((el.getOldValue()!="Q"&&el.val()=="Q")||(el.getOldValue()!="R"&&el.val()=="R")||(el.getOldValue()!="T"&&el.val()=="T")){
			    		self.master.beginTransaction();
			    		task[field] = el.val();
			    		task.reportType = el.val();
			    		
			    		self.master.endTransaction();
			    	}else{
			    		 self.master.beginTransaction();
		    			 task[field] = el.val();
		    			 self.master.endTransaction();
			    	}
			    	
			    	if (el.val() == "R" || el.val() == "Q"|| el.val() == "T"){
			    		 self.master.beginTransaction();
			    		task.reportType = el.val();
			    		 self.master.endTransaction();
			    	}else{
			    		 self.master.beginTransaction();
			    		task.reportType = "";
			    		 self.master.endTransaction();
			    	}
			    	
		    	}else if(field=='isMilestone'||field=='isPhase') {
		    		 self.master.beginTransaction();
	    			 task[field] = el.val()=="true"?true:false;
	    			 self.master.endTransaction();
		    	}else if(field=='principal'){
		    		if(task.isAssigned&&el.val()=="" ){
		    				alert("已发布的任务，任务负责人不能设置为空");
		    				self.master.beginTransaction();
							el.val(el.getOldValue());
							self.master.endTransaction();
							return false;
		    		}else{
		    			self.master.beginTransaction();
		    			 task[field] = el.val();
		    			 self.master.endTransaction();
		    		}
		    	}else if(field=='approver'){
		    		if(task.isAssigned&&el.val()=="" ){
		    			alert("已发布的任务，任务审批人不能设置为空");
		    			el.val(el.getOldValue());
		    			return false;
		    		}else{
		    			self.master.beginTransaction();
		    			task[field] = el.val();
		    			self.master.endTransaction();
		    		}
		    	}else {
		    		 self.master.beginTransaction();
	    			 task[field] = el.val();
	    			 self.master.endTransaction();
		    		
		    	}
		    }
	  });
	  
	  
	  
	  //binding on blur for task update (date exluded as click on calendar blur and then focus, so will always return false, its called refreshing the task row)
	  taskRow.find("input:text:not(.date)").focus(function () {
		  //console.dir("=============input:text:not(.date)==========================");
		  $(this).find(":input").updateOldValue();
	
	  }).blur(function (event) {
	    var el = $(this);
	    var row = el.closest("tr");
	    var taskId = row.attr("taskId");
	    var task = self.master.getTask(taskId);
	    //update task from editor
	    var field = el.prop("name");
	
	    if (el.isValueChanged()) {
	      self.master.beginTransaction();
	
	      if (field=="name"&&el.val() != ""&&el.val().length>120) {
	          alert(GanttMaster.messages["TASK_NAME_LENGTH_ERROR"]);
	          //el.val(el.getOldValue());
	          el.val(el[0].defaultValue);
	      }
	      if (field == "depends") {
	        var oldDeps = task.depends;
	        task.depends = el.val();
	
	        // update links
	        var linkOK = self.master.updateLinks(task);
	        if (linkOK) {
	          //synchronize status from superiors states
	          var sups = task.getSuperiors();
	/*
	          var oneFailed=false;
	          var oneUndefined=false;
	          var oneActive=false;
	          var oneSuspended=false;
	          var oneWaiting=false;
	          for (var i = 0; i < sups.length; i++) {
	            oneFailed=oneFailed|| sups[i].from.status=="STATUS_FAILED";
	            oneUndefined=oneUndefined|| sups[i].from.status=="STATUS_UNDEFINED";
	            oneActive=oneActive|| sups[i].from.status=="STATUS_ACTIVE";
	            oneSuspended=oneSuspended|| sups[i].from.status=="STATUS_SUSPENDED";
	            oneWaiting=oneWaiting|| sups[i].from.status=="STATUS_WAITING";
	          }
	
	          if (oneFailed){
	            task.changeStatus("STATUS_FAILED")
	          } else if (oneUndefined){
	            task.changeStatus("STATUS_UNDEFINED")
	          } else if (oneActive){
	            //task.changeStatus("STATUS_SUSPENDED")
	            task.changeStatus("STATUS_WAITING")
	          } else  if (oneSuspended){
	            task.changeStatus("STATUS_SUSPENDED")
	          } else  if (oneWaiting){
	            task.changeStatus("STATUS_WAITING")
	          } else {
	            var todoOk = task.changeStatus("STATUS_ACTIVE");
				  if(todoOk){
				  	task.taskStatusValue= 1;
				  }
	          }*/
	
	          self.master.changeTaskDeps(task); //dates recomputation from dependencies
	        }
	
	      } else if (field == "duration") {
	        var dates = resynchDates(el, row.find("[name=start]"), row.find("[name=startIsMilestone]"), row.find("[name=duration]"), row.find("[name=end]"), row.find("[name=endIsMilestone]"));
	        self.master.changeTaskDates(task, dates.start, dates.end);
	
	      } else if (field == "name" && el.val() == "") { // remove unfilled task
	        self.master.deleteCurrentTask(taskId);
	
	
	      } else if (field == "progress" ) {
	        task[field]=parseFloat(el.val())||0;
	        el.val(task[field]);
	
	      } else {
	    	  if(field=="name"){
	    		  if(task.activityId!=""||task.processId!=""||task.isFromTemplate==1)
	        		  task.master.needReason=true;
	    	  }
	        task[field] = el.val();
	      }
	      self.master.endTransaction();
	
	    } else if (field == "name" && el.val() == "") { // remove unfilled task even if not changed
	      if (task.getRow()!=0) {
	     //   self.master.deleteCurrentTask(taskId);

	      }else {
	        el.oneTime(1,"foc",function(){$(this).focus()}); //
	        event.preventDefault();
	        //return false;
	      }
	
	    }
	  });
	
	  //cursor key movement
	  taskRow.find("input").keydown(function (event) {
		  
		  //console.dir("=============input:input==========================");
	    var theCell = $(this);
	    var theTd = theCell.parent();
	    var theRow = theTd.parent();
	    var col = theTd.prevAll("td").length;
	
	    var ret = true;
	    if (!event.ctrlKey) {
	      switch (event.keyCode) {
	      case 13:
	        if (theCell.is(":text"))
	          theCell.blur();
	        break;
	
	        case 37: //left arrow
	          if (!theCell.is(":text") || (!this.selectionEnd || this.selectionEnd == 0))
	            theTd.prev().find("input").focus();
	          break;
	        case 39: //right arrow
	          if (!theCell.is(":text") || (!this.selectionEnd || this.selectionEnd == this.value.length))
	            theTd.next().find("input").focus();
	          break;
	
	        case 38: //up arrow
	          //var prevRow = theRow.prev();
	          var prevRow = theRow.prevAll(":visible:first");
	          var td = prevRow.find("td").eq(col);
	          var inp = td.find("input");
	
	          if (inp.length > 0)
	            inp.focus();
	          break;
	        case 40: //down arrow
	          //var nextRow = theRow.next();
	          var nextRow = theRow.nextAll(":visible:first");
	          var td = nextRow.find("td").eq(col);
	          var inp = td.find("input");
	          if (inp.length > 0)
	            inp.focus();
	          else
	            nextRow.click(); //create a new row
	          break;
	        case 36: //home
	          break;
	        case 35: //end
	          break;
	
	        case 9: //tab
	        case 13: //enter
	          break;
	      }
	    }
	    return ret;
	
	  }).focus(function () {
	    $(this).closest("tr").click();
	  });
  }

  //change status
  taskRow.find(".taskStatus").click(function () {
    /*var el = $(this);
    var tr = el.closest("[taskid]");
    var taskId = tr.attr("taskid");
    var task = self.master.getTask(taskId);

    var changer = $.JST.createFromTemplate({}, "CHANGE_STATUS");
    changer.find("[status=" + task.status + "]").addClass("selected");
    changer.find(".taskStatus").click(function (e) {
      e.stopPropagation();
      var newStatus = $(this).attr("status");
      changer.remove();
      self.master.beginTransaction();
      task.changeStatus(newStatus);
      self.master.endTransaction();
      el.attr("status", task.status);
    });
    el.oneTime(3000, "hideChanger", function () {
      changer.remove();
    });
    el.after(changer);*/
  });
  
  taskRow.find(".reportStatus").click(function () {
	  var el = $(this);
	  var tr = el.closest("[taskid]");
	  var taskId = tr.attr("taskid");
	  var task = self.master.getTask(taskId);
	 // alert(task.reportType);
	    if(task.reportType=="T"){
	    	
	    	selfMaster= self.master;
	    	
	    	var testReports = self.master.testReports;
	    	var testReport;
	    	for (var int = 0; int < testReports.length; int++) {
				if(testReports[int].testReportId ==  task.qualityReportId){
					testReport = testReports[int];
				}
			}
	    	//新增
	    	var relatedProject= task.relatedProject;
	    	if(testReport){
	    		//{"testReportId":89,"reportTitle":"2323","status":0,"testProjectId":149,"belongProjectId":149}
		    	 openNewWindow("/pm/processTestPlan.do?method=edit&inGant=true&relatedProject="+relatedProject+"&taskId="+taskId+"&projectId="+self.master.projectId
		    			 +"&testReportId="+testReport.testReportId
				    	 +"&securityLevel="+testReport.securityLevel
		    			 +"&reportTitle="+encodeURI(encodeURI(testReport.reportTitle))
		    			 +"&testProjectId="+testReport.testProjectId
		    			 +"&token="+escape(new Date()),'RWindow',0.6,0.7);
	    	}else{
	    		 openNewWindow("/pm/processTestPlan.do?method=add&inGant=true&relatedProject="+relatedProject+"&taskId="+taskId+"&projectId="+self.master.projectId+"&token="+escape(new Date()),'RWindow',0.6,0.7);
	    	}
	    	
	    	
	    	/*var reportEditor = $.JST.createFromTemplate(task, "TEST_REPORT_EDITOR");
	    	var testReports = self.master.testReports;
	    	var testReport;
	    	for (var int = 0; int < testReports.length; int++) {
				if(testReports[int].testReportId ==  task.qualityReportId){
					testReport = testReports[int];
				}
			}
	    	var ndo = createModalPopup(800, 350).append(reportEditor);//.append("<div style='height:800px; background-color:red;'></div>")
	    	 var nameEl = reportEditor.find("#name");
	    	 if(testReport){
	    		 reportEditor.find("#titleCreateOrUpdate").html("修改测试报告");
	    		 reportEditor.find("#disassociateTd").show();
	    		 nameEl.val(testReport.reportTitle);
	    	 }
	    	  var proEl = reportEditor.find("#project");
	    	  var opt = $("<option>");
	    	  proEl.append(opt);
	    	  for(var i=0; i< task.master.projects.length;i++){
	    	    var res = task.master.projects[i];
	    	    opt = $("<option>");
	    	    opt.val(res.id).html(res.name);
		    	 if(testReport){
			    	    if(testReport.testProjectId == res.id)
				    	      opt.attr("selected", "true");
		    		 
		    	 }
	    	    proEl.append(opt);
	    	  }
	    	  if(!testReport){
		    	  proEl.val(self.master.projectId);
	    	  }
	    	  var repEl = reportEditor.find("#existReport");
	    	 
	    	  for(var i=0; i< task.master.testReports.length;i++){
	    	    var res = task.master.testReports[i];
	    	    opt2 = $("<option>");
	    	    opt2.val(res.testReportId).html(res.reportTitle);
		    	if(testReport){
			    	    if(testReport.testReportId != res.testReportId){
				    	    repEl.append(opt2);
			    	    }
		    		 
		    	 }else{
			    	    repEl.append(opt2);
		    	 }
	    	  }
	    	  
	    	  reportEditor.find('input:radio[name="action"]').change(function() {
				if(this.checked){
					
					if(this.id=="action0"){
						reportEditor.find("#testReportNameTr").hide();
						reportEditor.find("#testReportPriojectTr").hide();
						reportEditor.find("#texistReportTr").show();
						reportEditor.find("#existReport").prop("disabled",false);
					}else if (this.id=="action2"){
						reportEditor.find("#testReportNameTr").hide();
						reportEditor.find("#testReportPriojectTr").hide();
						reportEditor.find("#texistReportTr").show();
						reportEditor.find("#existReport").prop("disabled",true);
					}else{
						reportEditor.find("#testReportNameTr").show();
						reportEditor.find("#testReportPriojectTr").show();
						reportEditor.find("#texistReportTr").hide();
						//reportEditor.find("#texistReportTr").attr("style","display:none");;
					}		
				}
			});
	    	  
	    	  
	    	  reportEditor.bind("saveTestReportEditor.gantt",function () {
	    	        //console.debug("saveTestReportEditor");

	    		 var testname=reportEditor.find("#name").val();
	    	      var action = reportEditor.find("input[name='action']:checked").val();
	    	      // console.debug(action);
	    	      if (action == 1){
	    	    	  if (testname&&testname!="") {
		    			 if (testname.length > 50) {
							alert("测试报告名称不能超过50个字");
							return;
		    			 }
		    		 }else{
		    			 alert("测试报告名称不能为空");
						return;
		    		 }
	    	      }
	    	      
	    	      if (action == 1){
	    	        if (testReport){ //修改报告
	    	        	   self.master.beginTransaction();
//	    	          if(!testReport.getStatus().equals("-1")&&havingChange()) {
//	    	            int result ;
//
//	    	            result = JOptionPane.showConfirmDialog(this,GantteResource.getResourceItem("gantte.testupdate"),
//	    	                                                   GantteResource.getResourceItem("gantte.testreport"),
//	    	                                                   JOptionPane.YES_NO_OPTION);
//	    	            if(result != 0) {
//	    	              return;
//	    	            }
//	    	          }
	    	          testReport.reportTitle = reportEditor.find("#name").val();
	    	          testReport.testProjectId = reportEditor.find("#project").val();
	    	          if(testReport.status==0) {
	    	            testReport.status=-2;
	    	          }
	    		      self.master.endTransaction();
	    	        } else{ //创建报告
	    	          self.master.beginTransaction();
	    	          var newTestReport = new TestReport(reportEditor.find("#name").val(), self.master.projectId, reportEditor.find("#project").val());
	    	          newTestReport.setNew();
	    	          newTestReport.status=-1;
	    	          newTestReport.testProjectId = reportEditor.find("#project").val();
	    	          self.master.testReports.push(newTestReport);
	    	          task.qualityReportId = newTestReport.testReportId;
	    	          self.master.endTransaction();
	    	        }
	    	      }
	    	      if (action == 0){
	    	    	  self.master.beginTransaction();
	    	          task.qualityReportId = reportEditor.find("#existReport").val();
	    	          self.master.endTransaction();

	    	      }
	    	      if (action == 2){
	    	    	  self.master.beginTransaction();
	    	          task.qualityReportId = -1;
	    	          self.master.endTransaction();
	    	      }
	    		  
    	          closeBlackPopup();

	    	      });*/
	    }else   if(task.reportType=="R"){
	    	//alert("R");
	    	if(taskId.indexOf("tmp")>=0){
	    		alert("已添加新任务，请先保存甘特图");
	    	}else if(task.master.__undoStack.length >0){
		    		alert("已修改任务，请先保存甘特图");
		    	}else{
	    		//alert("弹出"+taskId);
	    		var qualityReportId = task.qualityReportId;
	    		var relatedProject= task.relatedProject?task.relatedProject:"";
	    		if(qualityReportId){
	    			if(qualityReportId <=0){
	    				openNewWindow("/pm/reviewPlan.do?method=add&inGant=true&relatedProject="+relatedProject+"&taskId="+taskId+"&token="+escape(new Date()),'RWindow',0.6,0.7);
	    			}else{	    				
	    				openNewWindow("/pm/reviewPlan.do?method=show&inGant=true&inGant=true&taskId="+taskId+"&reportId="+qualityReportId+"&token="+escape(new Date()),'RWindow',0.6,0.7);
	    			}
	    		}else{
	    			openNewWindow("/pm/reviewPlan.do?method=add&inGant=true&relatedProject="+relatedProject+"&taskId="+taskId+"&token="+escape(new Date()),'RWindow',0.6,0.7);
	    			
	    		}
	    	}
	    }else   if(task.reportType=="Q"){
	    	//alert("R");
	    	if(taskId.indexOf("tmp")>=0){
	    		alert("已添加新任务，请先保存甘特图");
	    	}else if(task.master.__undoStack.length >0){
		    		alert("已修改任务，请先保存甘特图");
		    	}else{
	    		//alert("弹出"+taskId);
	    		var qualityReportId = task.qualityReportId;
	    	 	var relatedProject= task.relatedProject;
	    		if(qualityReportId){
	    			if(qualityReportId <=0){
	    				//window.showModalDialog("/pm/processAuditPlan.do?method=add&inGant=true&project_id="+self.master.projectId+"&taskId="+taskId+"&token="+escape(new Date()));
	    				openNewWindow("/pm/processAuditPlan.do?method=add&relatedProject="+relatedProject+"&inGant=true&project_id="+self.master.projectId+"&taskId="+taskId+"&token="+escape(new Date()),"QWindow",0.6,0.8);
	    			}else{	    				
	    				//window.showModalDialog("/pm/processAuditPlan.do?method=show&inGant=true&taskId="+taskId+"&reportId="+qualityReportId+"&token="+escape(new Date()));
	    				openWindow("/pm/processAuditPlan.do?method=show&inGant=true&project_id="+self.master.projectId+"&taskId="+taskId+"&reportId="+qualityReportId+"&token="+escape(new Date()),"QWindow");
	    			}
	    		}else{
	    			//window.showModalDialog("/pm/processAuditPlan.do?method=add&inGant=true&project_id="+self.master.projectId+"&taskId="+taskId+"&token="+escape(new Date()));
	    			openNewWindow("/pm/processAuditPlan.do?method=add&relatedProject="+relatedProject+"&inGant=true&project_id="+self.master.projectId+"&taskId="+taskId+"&token="+escape(new Date()),"QWindow",0.6,0.8);
	    			
	    		}
	    	}
	    }
  });
  
  
};
var oldType ="";


GridEditor.prototype.openFullEditor = function (task, editOnlyAssig) {
	
	
	var self = this;
	var windowHeight = 450;
	var windowWidth = 900;
	if (!self.master.permissions.canSeePopEdit)
		return;

	var taskRow = task.rowElement;

	// task editor in popup
	var taskId = taskRow.attr("taskId");

	self.master.setOldCycleAttribute(task,true);
	// make task editor
	var taskEditor;
	if (task.hasChild && task.id == 'tmp_-1') {
		windowWidth = 650;
		windowHeight = 400;

		taskEditor = $.JST.createFromTemplate(task, "TASK_PROJECT_EDITOR");
		taskEditor.find(".duration").prop("disabled", true);
		taskEditor.find("#name").prop("disabled", true);
		
		taskEditor.find("#name").val(task.name);
		taskEditor.find("#code").val(task.code);
		taskEditor.find("#duration").val(durationToString(task.duration));
		var startDate=taskEditor.find("#start");
		startDate.val(new Date(task.start).format());
		var endDate=taskEditor.find("#end");
		endDate.val(new Date(task.end).format());
		taskEditor.find(":input").updateOldValue();
		
		var empPmId=taskEditor.find("#empPmId").val();
		if(self.master.gantt.master.pmId!=empPmId||(editOnlyAssig&&!task.isLocked)){
			taskEditor.find("#rootConfirmbtnHR").attr("style","display:none");
			taskEditor.find("#rootConfirmbtn").attr("style","display:none");
			/*startDate.attr("style","display:none");;
			endDate.attr("style","display:none");*/
			startDate.hide();
			endDate.hide();
			taskEditor.find("#startTr").html(new Date(task.start).format());
			taskEditor.find("#endTr").html(new Date(task.end).format());
			windowHeight = 350;
		}
		
		//===============================================================
		// bind dateField on dates, duration
		taskEditor.find("#start,#end,#duration").click(function() {
			var input = $(this);
			if (input.is("[entrytype=DATE]")) {
				input.dateField({
					inputField : input,
					minDate : self.minAllowedDate,
					maxDate : self.maxAllowedDate,
					callback : function(d) {
						$(this).blur();
					}
				});
			}
		}).blur(
				function() {
					var inp = $(this);
					if (inp.validateField()) {
						resynchDates(inp, taskEditor.find("[name=start]"),
								taskEditor.find("[name=startIsMilestone]"),
								taskEditor.find("[name=duration]"), taskEditor
										.find("[name=end]"), taskEditor
										.find("[name=endIsMilestone]"));
						// workload computation
						if (typeof (workloadDatesChanged) == "function")
							workloadDatesChanged();
					}
				});

		taskEditor.find("#startIsMilestone,#endIsMilestone").click(
				function() {
					var inp = $(this);
					resynchDates(inp, taskEditor.find("[name=start]"),
							taskEditor.find("[name=startIsMilestone]"),
							taskEditor.find("[name=duration]"), taskEditor
									.find("[name=end]"), taskEditor
									.find("[name=endIsMilestone]"));
				});

		// task
		taskEditor.bind("fonfirmFullEditor.gantt",
				function() {

					var task = self.master.getTask(taskId); 

					var falg = true;
					if (Date.parseString(taskEditor.find("#start").val())
							.getTime() > Date.parseString(
							taskEditor.find("#end").val()).getTime()) {
						alert("计划开始时间不能晚于计划结束时间"+ taskEditor.find("#end").val());
						falg = false;
					}

					var starErrorDate, endErrorDate;
					var tableTasks = self.master.tasks;

					for ( var i = 0; i < self.master.tasks.length; i++) {
						var taskTable = self.master.tasks[i];
						//console.dir(Date.parseString(taskEditor.find("#start").val()).getTime());
						
						if (taskTable.id != task.id
								&& Date.parseString(
										taskEditor.find("#start").val())
										.getTime() > taskTable.start) {
							if (starErrorDate) {
								if (starErrorDate < taskTable.start) {
									starErrorDate = taskTable.start;
								}
							} else {
								starErrorDate = taskTable.start;
							}
						}
						if (taskTable.id != task.id&& Date.parseString(taskEditor.find("#end").val()).getTime() < taskTable.end&&taskEditor.find("#end").val()!=new Date(taskTable.end).format()) {
							if (endErrorDate) {
								if (endErrorDate < taskTable.end) {
									endErrorDate = taskTable.end;
								}
							} else {
								endErrorDate = taskTable.end;
							}
						}
					};


					if (falg&&starErrorDate) {
						alert("项目的计划开始时间不能晚于最早任务的计划开始时间"
								+ new Date(starErrorDate).format());
					}

					if (falg&&!starErrorDate && endErrorDate) {
						alert("项目的计划结束时间不能早于最晚的任务计划结束时间"
								+ new Date(endErrorDate).format());
					}

					if (falg && !endErrorDate && !starErrorDate) {
						// var task = self.master.getTask(taskId);
						self.master.beginTransaction();
						// task.setPeriod(Date.parseString(taskEditor.find("#start").val()).getTime(),
						// Date.parseString(taskEditor.find("#end").val()).getTime());
						task.start = Date.parseString(
								taskEditor.find("#start").val()).getTime();
						task.end = Date.parseString(
								taskEditor.find("#end").val()).getTime()

						var todoOk = false;
						if (task.status == "STATUS_ACTIVE"
								|| task.status == "STATUS_UNDEFINED") {
							if (taskEditor.find("#isAssigned").is(":checked")) {
								todoOk = task.changeStatus("STATUS_ACTIVE");
								if (todoOk) {
									task.taskStatusValue = 1;
								}
							} else {
								task.changeStatus("STATUS_UNDEFINED");

							}
						}
						if (self.master.endTransaction()) {
							taskEditor.find(":input").updateOldValue();
							closeBlackPopup();
						}
					}
				});
		
		createModalPopup(windowWidth, windowHeight).append(taskEditor);
		
	} else if(!task.canWrite){//not write
		taskEditor = $.JST.createFromTemplate(task, "TASK_TABLE_DETAILS");
		
		var ali = taskEditor.find(".tabTitle ul li");
		var aDiv = taskEditor.find(".tabContent .divTab");
		ali.each(function() {
			$(this).click(function() {
				var _this = $(this);
				_this.addClass('current').siblings().removeClass('current');
				var index = _this.index();
				aDiv.eq(index).show().siblings().hide();
			});
		});
		
		//=========================周期性任务Show===========start====================
		if(task.isLoop == "1"){
			taskEditor.find("#frequency").append(initFrequency());
			taskEditor.find("#frequency").val(task.frequency);
			taskEditor.find("#startDate").val((new Date(task.start).format()));
			taskEditor.find("#endDate").val((new Date(task.end).format()));
			if(task.isLoop == 1){
				taskEditor.find("#startDate").val((new Date(task.startDate).format()));
				taskEditor.find("#endDate").val((new Date(task.endDate).format()));
				taskEditor.find("#isMilestone").prop("disabled",true);
				taskEditor.find("#isPhase").prop("disabled",true);
			}
			if(task.repetition_type == 2 && task.typeLoop==1){//选中月份的情况
				taskEditor.find("#dayInput").val(task.day);
			}
			if(task.repetition_type == 3 && task.typeLoop==1){//选中月份的情况
				taskEditor.find("#dayInput").val(task.day);
			}
			
			taskEditor.find("#days").val(task.days);
			taskEditor.find("#workdelay").val(task.workdelay);
			taskEditor.find("#repetition_type").val(task.repetition_type);
			taskEditor.find("#times").val(task.times);
			taskEditor.find("#termType").val(task.termType);
			taskEditor.find("#isLoopLi").click(function(){
				loadFrequencySelect(task);
			});
			taskEditor.find("#repetition_type").change(function(){
				changeFrequency(task);
			});
			taskEditor.find("#termType").change(function(){
				termTypeChangeFn();
			});
			termTypeLoad(task);
			changeFrequency(task);//需要执行一次 显示数据
			taskEditor.find('input:radio[name="typeLoop"]').each(function(){
				var typeLoop = $(this).val();
				if(task.typeLoop == typeLoop){
					$(this).attr("checked","checked");
					$(this).attr("disabled","disabled");
				}
			});
		}else{
			taskEditor.find("#isLoopLi").hide();

		}
		//==================================周期性任务Show==========end=================
		
		
		var empPmId=taskEditor.find("#empPmId").val();
		//if(self.master.gantt.master.pmId!=empPmId){
		taskEditor.find("#nameTd").html(task.name);
		taskEditor.find("#typeTd").html(task.type);
		
		var lockedEmpName="";//锁定人员
		var principalTxt="";//任务负责人
		var approverTxt="";//任务审批人
		  for(var i=0; i< task.master.resources.length;i++){
			  var res = task.master.resources[i];
			  if(task.principal&&task.principal==res.id){
				  principalTxt=res.name;
			  }
			  if(task.lockedEmpId&&task.lockedEmpId==res.id){
				  lockedEmpName=res.name;
			  }
			  if(task.approver&&task.approver==res.id){
				  approverTxt=res.name;
			  }
		  }
		  
		taskEditor.find("#principal_txt").html(principalTxt);
		taskEditor.find("#isLocked_txt").html(task.isLocked?lockedEmpName:"未锁定");
		taskEditor.find("#coordinateEdit_txt").html(task.coordinateEdit?principalTxt:"未协同");
	
		//debugger;
		taskEditor.find("#startdateTd").attr("style","display:block");
		taskEditor.find("#startdateTd").html(new Date(task.start).format());
		//taskEditor.find("#startdateTdinput").html("<input type=\"text\" name=\"start\" id=\"start\" size=\"8\" >");
		taskEditor.find("#enddateTd").attr("style","display:block");
		taskEditor.find("#enddateTd").html(new Date(task.end).format());
		
		/*taskEditor.find(".realstart_txt").html(task.realstart!="-1"?new Date(task.realstart).format():new Date(task.start).format());
		taskEditor.find(".realend_txt").html(task.realend!="-1"? new Date(task.realend).format(): new Date(task.end).format());*/

		taskEditor.find(".realstart_txt").html(((!(task.realstart))||task.realstart<0)?"":new Date(task.realstart).format());
		taskEditor.find(".realend_txt").html(((!(task.realend))||task.realend<0)?"":new Date(task.realend).format());
		
		taskEditor.find(".planWorkload_txt").html((task.planWorkload?task.planWorkload:"0")+" (小时)");
		taskEditor.find(".realWorkload_txt").html((task.realWorkload?task.realWorkload:"0")+" (小时)");
		taskEditor.find("#relatedProject_txt").html(getRelatedProjectName(task.relatedProject,task));
		
		taskEditor.find("#duration_txt").html(task.duration+" (天)");
		taskEditor.find("#isPhase_txt").html(task.isPhase?"是阶段":"不是阶段");
		taskEditor.find("#isMilestone_txt").html(task.isMilestone?"是里程碑":"不是里程碑");
		
		taskEditor.find("#approver_txt").html(approverTxt);

		taskEditor.find(".del").remove();
		taskEditor.find(".delWp").remove();
		taskEditor.find("#descriptionTd").html(task.description);
		
		if (editOnlyAssig) {
			taskEditor.find("#wordLi").attr("style","display:none");
			taskEditor.find("#isAssignedTr").attr("style","display:none");
			taskEditor.find("#detailedInfo").attr("style","display:none");
			//taskEditor.find(".taskData").hide();
			taskEditor.find("#taskUser").addClass('current').siblings().removeClass('current');
			taskEditor.find(".tabContent .divTab").eq(0).attr("style","display:none");
			taskEditor.find(".tabContent .divTab").eq(1).attr("style","display:block");
			taskEditor.find("#approverTitle").attr("style","display:block");
			taskEditor.find("#assigsTable").show();
			taskEditor.find("#approverTitle").show();
			taskEditor.find("#taskUser").attr("style","display:none");
			taskEditor.find("#firstHR").attr("style","display:none");
			taskEditor.find("#titleTask").html("选择成员");
			taskEditor.find("#isLoopLi").hide();
		  }else{
			 
		  }
		
		var assigsTable = taskEditor.find("#assigsTable");
		assigsTable.find("[assId]").remove();
		// loop on assignments
		for ( var i = 0; i < task.assigs.length; i++) {
			var assig = task.assigs[i];
			var acTypeId = task.typeId;
			var assigRow = $.JST.createFromTemplate({
				task : task,
				assig : assig,
				resourceName_txt:getResourcesName(assig.resourceId,task),
				principalRadio : assig.resourceId&&task.principal==assig.resourceId,
				acTypeId : acTypeId
			}, "ASSIGNMENT_ROW");
			
			assigRow.find("[name=resourceId]").attr("style","display:none");
			assigRow.find("#resourceName_txt").attr("style","display:block");
			assigRow.find("[name=effort]").attr("style","display:none");
			assigRow.find("#principalRadioId").prop("disabled", true);
			assigRow.find("#effort_txt").attr("style","display:block");
			//assigRow.find(".del").attr("style","display:none");
			assigRow.find("#del").remove();
			assigsTable.append(assigRow);
		}
	
		var wpTable = taskEditor.find("#wpTable");
		wpTable.find("[productId]").remove();
		// loop on assignments
		for ( var i = 0; i < task.workProduct.length; i++) {
			var wp = task.workProduct[i];
			var wpRow = $.JST.createFromTemplate({
				wp : wp
			}, "WORKPRODUCT_ROW");
			
			wpRow.find("#planSize_txt").attr("style","display:block");
			wpRow.find("[name=planSize]").attr("style","display:none");
			wpRow.find("#delWp").remove();
			wpTable.append(wpRow);
		}
		var dpTable = taskEditor.find("#dpTable");
		var ccurdepends = task.depends;
		if(ccurdepends.length>0){
			
			var dArray = ccurdepends.split(",");
			for ( var i = 0; i < dArray.length; i++) {
				var dp = dArray[i];
				var dpRow = $.JST.createFromTemplate({
					task : task,
					dp : dp
				}, "DEPENDS_ROW");
				dpRow.find("#taskId_txt").attr("style","display:block");
				dpRow.find("[name=taskId]").attr("style","display:none");
				dpRow.find("#type_txt").attr("style","display:block");
				dpRow.find("[name=type]").attr("style","display:none");
				dpRow.find("#delayDay_txt").attr("style","display:block");
				dpRow.find("[name=delayDay]").attr("style","display:none");
				dpRow.find("#delDp").remove();
				dpTable.append(dpRow);
				//$("select.assSelect").select2();
			}
		}
		createModalPopup(windowWidth, windowHeight).append(taskEditor);
		
	} else {
		taskEditor = $.JST.createFromTemplate(task, "TASK_EDITOR");
		//=========================table==========start====================
		//Tab页签切换
		var ali = taskEditor.find(".tabTitle ul li");
		var aDiv = taskEditor.find(".tabContent .divTab");
		ali.each(function() {
			$(this).click(function() {
				var _this = $(this);
				_this.addClass('current').siblings().removeClass('current');
				var index = _this.index();
				aDiv.eq(index).show().siblings().hide();
			});
		});
		//=========================周期性任务===========start====================
		taskEditor.find("#frequency").append(initFrequency());
		taskEditor.find("#frequency").val(task.frequency);
		taskEditor.find("#startDate").val((new Date(task.start).format()));
		taskEditor.find("#endDate").val((new Date(task.end).format()));
		if(task.isLoop == 1){
			taskEditor.find("#startDate").val((new Date(task.startDate).format()));
			taskEditor.find("#endDate").val((new Date(task.endDate).format()));
			taskEditor.find("#isMilestone").prop("disabled",true);
			taskEditor.find("#isPhase").prop("disabled",true);
		}
		if(task.repetition_type == 2 && task.typeLoop==1){//选中月份的情况
			taskEditor.find("#dayInput").val(task.day);
		}
		if(task.repetition_type == 3 && task.typeLoop==1){//选中月份的情况
			taskEditor.find("#dayInput").val(task.day);
		}
		
		taskEditor.find("#days").val(task.days);
		taskEditor.find("#workdelay").val(task.workdelay);
		taskEditor.find("#repetition_type").val(task.repetition_type);
		taskEditor.find("#times").val(task.times);
		taskEditor.find("#termType").val(task.termType);
		taskEditor.find("#isLoopLi").click(function(){
			loadFrequencySelect(task);
		});
		taskEditor.find("#repetition_type").change(function(){
			changeFrequency(task);
		});
		taskEditor.find("#termType").change(function(){
			termTypeChangeFn();
		});
		termTypeLoad(task);
		changeFrequency(task);//需要执行一次 显示数据
		taskEditor.find('input:radio[name="typeLoop"]').each(function(){

			var typeLoop = $(this).val();
			if(task.typeLoop == typeLoop){
				$(this).attr("checked","checked");
			}
		});
		//==================================周期性任务==========end=================
		
	    var taskTrRow = self.master.getTask(taskId);

		if(!task.approver||task.approver==""){
			var parents;
			var futureParents = task.getParents();
			if (futureParents.length > 0){
				for ( var i = 0; i < futureParents.length; i++) {
					if (futureParents[i].id!="tmp_-1") {
						if(parents){
							if(futureParents[i].level>parents){
								parents=futureParents[i];
							}
						}else{
							parents=futureParents[i];
						}
					}
				}
			}
			
			if(parents){
				task.approver=parents.approver;
			}else{
				task.approver=self.master.gantt.master.pmId;
			}
		}

		// hide task data if editing assig only
		var childrenTask = task.getChildren();
		if (editOnlyAssig && !task.isProjectRoot) {//editOnlyAssig协同//成员
			//taskEditor.find(".taskData").hide();
			//taskEditor.find("#wpTitle").hide();
			//taskEditor.find("#wpTable").hide();
			//taskEditor.find("#principal").show();
			//taskEditor.find(".assigsTableWrapper").height(465);
			//taskEditor.prepend("<h3>任务名称：" + task.name + "</h3>");
			//成员
			taskEditor.find("#wordLi").attr("style","display:none");
			taskEditor.find("#isAssignedTr").attr("style","display:none");
			taskEditor.find("#rootConfirmbtnP").attr("style","margin-left:25rem");
			
			taskEditor.find("#detailedInfo").attr("style","display:none");
			//taskEditor.find(".taskData").hide();
			taskEditor.find("#taskUser").addClass('current').siblings().removeClass('current');
			taskEditor.find(".tabContent .divTab").eq(0).attr("style","display:none");
			taskEditor.find(".tabContent .divTab").eq(1).attr("style","display:block");
			taskEditor.find("#approverTitle").attr("style","display:block");
			taskEditor.find("#assigsTable").show();
			taskEditor.find("#approverTitle").show();
			taskEditor.find("#firstHR").attr("style","display:none");
			taskEditor.find("#titleTask").html("选择成员");
			taskEditor.find("#isLoopLi").hide();
			//if(self.master.gantt.master.pmId!=empPmId||(editOnlyAssig&&!task.isLocked)){

		}else{
			
			
			var qualityReportId= task.qualityReportId;
	    	if((task.typeId=="Q"||task.typeId=="T"||task.typeId=="R")&&qualityReportId&&qualityReportId!=""){
	    		taskEditor.find("#relatedProject").prop("disabled",true);
	    	}else{
	    		taskEditor.find("#relatedProject").prop("disabled",false);
	    	}
			
			if (task.hasChild){
                for (var i in childrenTask){
                   // if(childrenTask[i].status != 'STATUS_UNDEFINED'){
                	if(task.isLoop!=""&&task.isLoop != "0"){
                        taskEditor.find("select[name='repetition_type'] option[value='-1']").remove();
                        /*taskEditor.find("#isAssigned").prop("checked", true);*/
                        break;
                    }
                }
				if(task.isLoop != "1"){
					taskEditor.find("#isLoopLi").hide();
				}
				
				taskEditor.find("#duration").attr("readonly", "true");

				taskEditor.find("[name=principal]").val(task.principal);

				taskEditor.find("#start").prop("disabled", true);
				taskEditor.find("#end").prop("disabled", true);
				
			}else{

				taskEditor.find("#start").show();
				taskEditor.find("#end").show();
                if(task.isLoop == '1'){
                  //  taskEditor.find("#isLoopLi").hide();
                    taskEditor.find("#isPhase").prop("disabled",true);
                }
                //console.dir(task.getParent().isLoop);
				if(task.isLoop == '2'||task.getParent().isLoop=='1'){
					taskEditor.find("#isLoopLi").hide();
					//taskEditor.find("#isPhase").prop("disabled",true);
				}
				if(task.isLoop == "0" && task.status !="STATUS_UNDEFINED" ){
					taskEditor.find("#isLoopLi").hide();
				}
				for (var i in childrenTask){
					if(childrenTask[i].isLoop != "2" && childrenTask[i].status !="STATUS_UNDEFINED"){
						taskEditor.find("#isLoopLi").hide();
						break;
					}
				}
		    }
		}
		
		if (editOnlyAssig){
			taskEditor.find("#firstHR").attr("style","display:none");
			taskEditor.find("#taskUser").attr("style","display:none");
			taskEditor.find("#titleH").attr("style","display:block");
			taskEditor.find("#titleTask").html("选择成员");
		}
	
		// got to extended editor
		// if (task.isNew()|| !self.master.permissions.canSeeFullEdit){
		taskEditor.find("#taskFullEditor").remove();
		// } else {
		// taskEditor.bind("openFullEditor.gantt",function () {
		// window.location.href=contextPath+"/applications/teamwork/task/taskEditor.jsp?CM=ED&OBJID="+task.id;
		// });
		// }
	
		taskEditor.find("#name").val(task.name);
		taskEditor.find("#description").val(task.description);
		taskEditor.find("#code").val(task.code);
		taskEditor.find("#progress").val(
				task.progress ? parseFloat(task.progress) : 0).prop("readonly",
				task.progressByWorklog == true);
		taskEditor.find("#progressByWorklog").prop("checked",
				task.progressByWorklog);
		taskEditor.find("#status").val(task.status);
		taskEditor.find("#type").val(task.typeId);
		taskEditor.find("#type_txt").val(task.type);
		//taskEditor.find("#relevance").val(task.relevance);
		
		taskEditor.find(".relevance_txt").html(((!(task.realstart))||task.realstart<0)?"":new Date(task.realstart).format());
		taskEditor.find(".realend_txt").html(((!(task.realend))||task.realend<0)?"":new Date(task.realend).format());
	
		if (task.startIsMilestone)
			taskEditor.find("#startIsMilestone").prop("checked", true);
		if (task.endIsMilestone)
			taskEditor.find("#endIsMilestone").prop("checked", true);
	
		taskEditor.find("#duration").val(durationToString(task.duration));
		var startDate = taskEditor.find("#start");
		startDate.val(new Date(task.start).format());
		// taskEditor.find(".start").html(new Date(task.start).format());
		taskEditor.find(".hideTd").prop("disabled", true);
		// start is readonly in case of deps
		if (task.depends || !task.canWrite) {
			startDate.attr("readonly", "true");
		} else {
			startDate.removeAttr("readonly");
			//taskEditor.find(".duration").prop("disabled", false);
		}
	
		taskEditor.find("#end").val(new Date(task.end).format());
		// taskEditor.find(".end").html(new Date(task.end).format());
		// make assignments table
		var assigsTable = taskEditor.find("#assigsTable");
		assigsTable.find("[assId]").remove();
		// loop on assignments
		for ( var i = 0; i < task.assigs.length; i++) {
			var assig = task.assigs[i];
			var acTypeId = task.typeId;
			var assigRow = $.JST.createFromTemplate({
				task : task,
				assig : assig,
				principalRadio : assig.resourceId&&task.principal==assig.resourceId,
				acTypeId : acTypeId
			}, "ASSIGNMENT_ROW");
			  
			assigsTable.append(assigRow);
		}
				
		var wpTable = taskEditor.find("#wpTable");
		wpTable.find("[productId]").remove();
		// loop on assignments
		for ( var i = 0; i < task.workProduct.length; i++) {
			var wp = task.workProduct[i];
			var wpRow = $.JST.createFromTemplate({
				wp : wp
			}, "WORKPRODUCT_ROW");
			wpTable.append(wpRow);
		}
	
		var dpTable = taskEditor.find("#dpTable");
		dpTable.find("[depends]").remove();
		// loop on depends
		var ccurdepends = task.depends;
		if(ccurdepends.length>0){
			
			var dArray = ccurdepends.split(",");
			for ( var i = 0; i < dArray.length; i++) {
				var dp = dArray[i];
				var dpRow = $.JST.createFromTemplate({
					task : task,
					dp : dp
				}, "DEPENDS_ROW");
				dpTable.append(dpRow);
				//$("select.assSelect").select2();
			}
		}
	
		wpCurrenttaskId = taskId;
		taskEditor.find(":input").updateOldValue();
		if ((!task.canWrite)) {
			taskEditor.find("input,textarea").prop("readOnly", true);
			taskEditor.find("input:checkbox,select").prop("disabled", true);
			taskEditor.find("#saveButton").remove();
			taskEditor.find(".button").addClass("disabled");
			taskEditor.find(".delAssig").hide();
			taskEditor.find(".delWp").hide();
			
		} else {
			if (task.hasChild) {// 父节点
				 taskEditor.find("#isAssignedTr").show();
				 taskEditor.find("#isAssigned").prop("disabled", true);
				// taskEditor.find("#rootConfirmbtnP").attr("style","margin-left:25rem");

				taskEditor.find("#duration").prop("disabled", true);
				
                if(task.isLoop == '0'&&task.canWrite&&!(task.isParent() && task.master.shrinkParent)){
               		taskEditor.find("#isPhase").removeAttr("disabled");
                    taskEditor.find("#isMilestone").removeAttr("disabled");
                }
				
				taskEditor.find("#start").prop("readOnly", true);
				taskEditor.find("#end").prop("readOnly", true);

				taskEditor.find("#duration").prop("readOnly", true);
				taskEditor.find("#saveButton").hide();
				windowHeight = 200;
				if(task.isLoop == "0" && task.status !="STATUS_UNDEFINED" ){
					taskEditor.find("#isLoopLi").hide();
				}
			} else if (task.getChildren().length > 0) {//未保存父节点
				
                var childrenTask =task.getChildren();
                for (var i in childrenTask){
                    if(task.isLoop != "0"){
                        taskEditor.find("select[name='repetition_type'] option[value='-1']").remove();
                        /*taskEditor.find("#isAssigned").prop("checked", true);*/
                        break;
                    }
                }
				//if(task.isLoop == "0" && task.status !="STATUS_UNDEFINED" ){
				if(task.isLoop == "0"  ){
					taskEditor.find("#isLoopLi").hide();
				}
				taskEditor.find("#isAssigned").prop("disabled", true);
				taskEditor.find("#type").prop("disabled", true);
				if(task.isLoop=='1'){
					taskEditor.find("#type").prop("disabled", false);
				}
				taskEditor.find("#start").prop("disabled", true);
				taskEditor.find("#end").prop("disabled", true);
				taskEditor.find("#duration").prop("disabled", true);
                if(task.isLoop == '1'){
                    taskEditor.find("#isPhase").prop("disabled",true);
				}

			}
			if (task.isProjectRoot) {
				//alert("子节点点1");
				taskEditor.find("#name").prop("disabled", true);
				taskEditor.find("#principal").prop("disabled", true);
				taskEditor.find("#approver").prop("disabled", true);
				taskEditor.find("#relatedProject").prop("disabled", true);
				taskEditor.find("#description").prop("disabled", true);
				taskEditor.find("#isMilestone").prop("disabled", true);
				//taskEditor.find("#isPhase").prop("disabled", true);
				taskEditor.find("#assigsTable").hide();
				taskEditor.find("#assigsTable").prev().hide();
				//console.dir(9);
			}
	
			if (task.isProjectRoot && task.master.canModifyProject) {
	
				taskEditor.find("#start").prop("disabled", false);
				taskEditor.find("#end").prop("disabled", false);
				//taskEditor.find("#duration").prop("disabled", false);
				if(task.isProjectRoot){
					taskEditor.find("#rootConfirmbtnHR").attr("style","display:block");

				}
			
			} else {
				// bind add assignment
				var cnt = 0;
				var neweffort=0;
				var durationNum=getWorkDayCountNum(self.master.projectId,new Date(taskEditor.find("#start").val()).format(),new Date(taskEditor.find("#end").val()).format());
				if(durationNum===''){
					durationNum=0;
					neweffort=durationNum;
				}else{
					neweffort=durationNum*self.master.gantt.master.fulleffort;
				}
				
					taskEditor.find("#addAssig").click(
							function() {
								cnt++;
								var assigsTable = taskEditor.find("#assigsTable");
								var acTypeId = task.typeId;
								if (taskEditor.find("#type").val()
										&& taskEditor.find("#type").val() != acTypeId) {
									acTypeId = taskEditor.find("#type").val();
								}
								var assigRow = $.JST.createFromTemplate({
									task : task,
									assig : {
											id : "tmp_" + new Date().getTime() + "_" + cnt
									},
									acTypeId : acTypeId
								}, "ASSIGNMENT_ROW");
								
								assigRow.find('[name="resourceId"]').change(function() {
									var num=0;
									var assigRowT = $(this);
									
									if(assigRowT.val()!=""){
										//alert(assigRowT.val());
										assigsTable.find("tr[assId]").each(
												function() {
													var trAss = $(this);
													var resourceId = trAss.find("[name=resourceId]").val();	
													if(assigRowT.val()==resourceId){
														num++;
													}
											});
									}
									
									if(assigRowT.val()!=""&&num>1){
										alert("已存在【"+getResourcesName(assigRowT.val(),task)+"】,不可重复添加");
										assigRowT.val("");
									}else{
										if(assigRowT.val()!=""&&assigRow.find("[name=effort]").val()==""){
											assigRow.find("[name=effort]").val(neweffort);
										}
									}
							});
							
							
							assigsTable.append(assigRow);
							

							//$("select.assSelect").select2();
							//$("#approver").select2();
							$("#bwinPopupd").scrollTop(10000);
						}
					).click();
	
					taskEditor.find("#addDp").click(
						function() {
						var dpTable =  taskEditor.find("#dpTable");
						var dpRow = $.JST.createFromTemplate({
								task : task									 
							}, "DEPENDS_ROW");
//						dpRow.find('[name="taskId"]').change(function (){
//							changeDepends($(this), dpTable, dpRow);
//						});
						dpTable.append(dpRow);
						//$("select.assSelect").select2();
						}
					);
				
					taskEditor.find("#addWp").click(function() {
						insertWP(self.master.projectId);
					});
	
			}
	}
//=========================table===end=========================================		
		
		
		 var futureParents = task.getParents();
		 var parents;
		 if (futureParents.length > 0){
			for ( var i = 0; i < futureParents.length; i++) {
				if (parents&&futureParents[i].id=="tmp_-1") {
					parents=futureParents[i];
				}
			}
		}
		 
		 var falg = true;

		 if(parents){
			 var falg = true;
				if (parents.start > Date.parseString(taskEditor.find("#end").val()).getTime()) {
					alert("计划开始时间不能晚于计划结束时间"+ taskEditor.find("#end").val());
					falg = false;
				}
				if (parents.end < Date.parseString(taskEditor.find("#end").val()).getTime()) {
					alert("计划开始时间不能晚于计划结束时间"+ taskEditor.find("#end").val());
					falg = false;
				} 
		 }
		taskEditor.find("#startDate,#endDate").click(function(){
			var input = $(this);
			var task = self.master.getTask(taskId);
			if (input.is("[entrytype=LOOP_DATE]")) {
				input.dateField({
					inputField : input,
					minDate : self.minAllowedDate,
					maxDate : self.maxAllowedDate,
					callback : function(d) {
						var parents	=getTaskDateChangeValue(task);
						var loopFlag = false;
						var startDate = Date.parseString(taskEditor.find("[name=startDate]").val()).getTime();
						var endDate = Date.parseString(taskEditor.find("[name=endDate]").val()).getTime();
						if(parents){
							if (parents.start >startDate ) {
								if(self.master.gantt.master.pmId!=self.master.gantt.master.currentEmpId&&task.isLocked){
									alert("计划开始时间早于项目开始日期，不能调整");
									loopFlag = false;
								}else if(self.master.gantt.master.pmId==self.master.gantt.master.currentEmpId){
									loopFlag=confirm("你的操作引起了项目开始日期的修改，是否修改项目的开始日期为【"+Date.parseString(taskEditor.find("[name=startDate]").val()).format()+"】？");
								}
							}
						/*	if (parents.end < endDate) {
								if(self.master.gantt.master.pmId!=self.master.gantt.master.currentEmpId&&task.isLocked){
									alert("计划结束时间晚于项目结束日期，不能调整");
									loopFlag = false;
								}else if(self.master.gantt.master.pmId==self.master.gantt.master.currentEmpId){
									loopFlag=confirm("你的操作引起了项目结束日期的修改，是否修改项目的结束日期为【"+Date.parseString(taskEditor.find("[name=endDate]").val()).format()+"】？");
								}
							}*/
							if(loopFlag){
								task.startDate=new Date(startDate).format();
								taskEditor.find("[name=start]").val(new Date(startDate).format());
								taskEditor.find("[name=end]").val(new Date(endDate).format());
								var inp = $(this);
								resynchDates(inp, taskEditor.find("[name=start]"),
									taskEditor.find("[name=startIsMilestone]"),
									taskEditor.find("[name=duration]"), taskEditor
										.find("[name=end]"), taskEditor
										.find("[name=endIsMilestone]"));
								// workload computation

								if (typeof (workloadDatesChanged) == "function")
									workloadDatesChanged();
							}
						}

					}
				});
			}
			else if(input.is("[entrytype=LOOP_DATE_END]")){
				input.dateField({
					inputField : input,
					minDate : self.minAllowedDate,
					maxDate : self.maxAllowedDate,
					callback : function(d) {
						var startDate = Date.parseString(taskEditor.find("[name=startDate]").val()).getTime();
						var endDate = Date.parseString(taskEditor.find("[name=endDate]").val()).getTime();
						task.startDate=new Date(startDate).format();
						taskEditor.find("[name=start]").val(new Date(startDate).format());
						taskEditor.find("[name=end]").val(new Date(endDate).format());
						var inp = $(this);
						resynchDates(inp, taskEditor.find("[name=start]"),
							taskEditor.find("[name=startIsMilestone]"),
							taskEditor.find("[name=duration]"), taskEditor
								.find("[name=end]"), taskEditor
								.find("[name=endIsMilestone]"));
						// workload computation

						if (typeof (workloadDatesChanged) == "function")
							workloadDatesChanged();
					}
				});
			}
		});
		// bind dateField on dates, duration
		taskEditor.find("#start,#end,#duration").click(function() {
			var input = $(this);
			if (input.is("[entrytype=DATE]")) {
				input.dateField({
					inputField : input,
					minDate : self.minAllowedDate,
					maxDate : self.maxAllowedDate,
					callback : function(d) {
						$(this).blur();
					}
				});
			}
		}).blur(
				function() {
					var parents	=getTaskDateChangeValue(task);
					var falg=true;
					if(parents){
						if (parents.start > Date.parseString(taskEditor.find("[name=start]").val()).getTime()) {
							if(self.master.gantt.master.pmId!=self.master.gantt.master.currentEmpId&&task.isLocked){
								alert("计划开始时间早于项目开始日期，不能调整");
								falg = false;
							}else if(self.master.gantt.master.pmId==self.master.gantt.master.currentEmpId){
								falg=confirm("计划开始时间早于项目开始日期，是否修改项目的开始日期为【"+Date.parseString(taskEditor.find("[name=start]").val()).format()+"】？");
							}
						}
						if (parents.end < Date.parseString(taskEditor.find("[name=end]").val()).getTime()) {
							if(self.master.gantt.master.pmId!=self.master.gantt.master.currentEmpId&&task.isLocked){
								alert("计划结束时间晚于项目结束日期，不能调整");
								falg = false;
							}else if(self.master.gantt.master.pmId==self.master.gantt.master.currentEmpId){
								falg=confirm("计划结束时间晚于项目结束日期，是否修改项目的结束日期为【"+Date.parseString(taskEditor.find("[name=end]").val()).format()+"】？");
							}
						}
					}
					
					if(falg){
						var inp = $(this);
						if (inp.validateField()) {
							resynchDates(inp, taskEditor.find("[name=start]"),
									taskEditor.find("[name=startIsMilestone]"),
									taskEditor.find("[name=duration]"), taskEditor
											.find("[name=end]"), taskEditor
											.find("[name=endIsMilestone]"));
							// workload computation
							if (typeof (workloadDatesChanged) == "function")
								workloadDatesChanged();
						}
					}else{
						inp.val(inp.getOldValue());
						return false;
					}
				});

		taskEditor.find("#startF,#endIsMilestone").click(
				function() {
					var inp = $(this);
					resynchDates(inp, taskEditor.find("[name=start]"),
							taskEditor.find("[name=startIsMilestone]"),
							taskEditor.find("[name=duration]"), taskEditor
									.find("[name=end]"), taskEditor
									.find("[name=endIsMilestone]"));
				});

		
		taskEditor.find("select").focus(function () {
			  $(this).updateOldValue();
		
		  }).blur(function (event) {
			  var el = $(this);
				var task = self.master.getTask(taskId);

			    //update task from editor
			    var field = el.prop("name");
			    if (el.isValueChanged()) {
			    	if(field=='type'){
			    		var qualityReportId= task.qualityReportId;
				    	if((el.getOldValue()=="Q"||el.getOldValue()=="T"||el.getOldValue()=="R")&&el.val()!="Q"&&el.val()!="T"&&el.val()!="R"&&qualityReportId&&qualityReportId!=""){
				    		if(!confirm("任务已经填过质量报告, 修改任务类型将取消与质量报告、相关质量数据的关联！")){
				    			el.val(el.getOldValue());
				    		}else{
				    			 self.master.beginTransaction();
				    			 task[field] = el.val();
				    		     task.reportType = "";
				    		     task.qualityReportId = "";
				    			 self.master.endTransaction();
				    			 //self.editor.refreshExpandStatus(task);
				    		}
				    	}else if((el.getOldValue()=="Q"||el.getOldValue()=="T"||el.getOldValue()=="R")&&(el.val()=="Q"||el.val()=="T"||el.val()=="R")&&qualityReportId&&qualityReportId!=""){
							 if(!confirm("任务已经填过质量报告, 修改任务类型将取消与质量报告、相关质量数据的关联！")){
					  			el.val(el.getOldValue());
					  		}else{
					  			 self.master.beginTransaction();
					  			 task[field] = el.val();
					  		     task.reportType =el.val();
					  		     task.qualityReportId = "";
					  			 self.master.endTransaction();
					  			// self.editor.refreshExpandStatus(task);
					  		}
				    	}else if((el.getOldValue()!="Q"&&el.val()=="Q")||(el.getOldValue()!="R"&&el.val()=="R")||(el.getOldValue()!="T"&&el.val()=="T")){
				    		self.master.beginTransaction();
				    		task[field] = el.val();
				    		task.reportType = el.val();
				    		
				    		self.master.endTransaction();
				    	}else{
				    		 self.master.beginTransaction();
			    			 task[field] = el.val();
			    			 self.master.endTransaction();
				    	}
				    	
				    	if (el.val() == "R" || el.val() == "Q"|| el.val() == "T"){
				    		task.reportType = el.val();
				    	}else{
				    		task.reportType = "";
				    	}
				    	
			    	}else if(field=='isMilestone'||field=='isPhase') {
			    		 self.master.beginTransaction();
		    			 task[field] = el.val()=="true"?true:false;
		    			 self.master.endTransaction();
			    		
			    	}else {
			    		 self.master.beginTransaction();
		    			 task[field] = el.val();
		    			 self.master.endTransaction();
			    		
			    	}
			    }
		  });
		  

		// save task
		taskEditor.bind("saveFullEditor.gantt",function() {
			// console.debug("saveFullEditor");
			var task = self.master.getTask(taskId); // get task
													// again
													// because
													// in case
													// of
													// rollback
													// old task
													// is lost

				if (taskEditor.find("#isAssigned").is(":checked")) {
					// alert("checking");
					// alert(taskEditor.find("#approver").val());
					// alert(taskEditor.find("#approver").val());
					var principalSelect = taskEditor.find("#principal option:selected").val();
							
					var approver = taskEditor.find("#approver").val();

					/*if (!principal&&principal.length < 1) {
						alert("未选择任务负责人");
						return;
					}*/
					if (approver.length < 1) {
						alert("未选择任务审批人");
						return;
					}
				}

				if (task.hasChild) {
					if (taskEditor.find("#description").val().length > 500) {
						alert("任务描述过长，请不要超过500个字");
						return;
					}
				}else{
					if (taskEditor.find("#description").val().length > 500) {
						alert("任务描述过长，请不要超过500个字");
						return;
					}
				}
				
				if (taskEditor.find("#name").val().length > 120) {
					alert("任务名称过长，请不要超过120个字");
					return;
				}
				if (taskEditor.find("#name").val().length == 0) {
					alert("请输入任务名称");
					return;
				}
				// if(!isNumber(taskEditor.find("#times").val())){
				// 	alert("限定次数请填数字!");
				// 	taskEditor.find("#times").val(1);
				// 	return
				// }
				if((taskEditor.find("#times").val()*1)<0){
					alert("限定次数不能小于0!");
					taskEditor.find("#times").val(1);
					return
				}
				// if(!isNumber(taskEditor.find("#workdelay").val())){
				// 	alert("工期请填数字!");
				// 	taskEditor.find("#workdelay").val(1);
				// 	return
				// }
				if((taskEditor.find("#workdelay").val()*1)<0){
					alert("工期不能小于0!");
					taskEditor.find("#workdelay").val(1);
					return
				}
				var resourceId;
				var lengofDay = taskEditor.find("#duration").val();
				var toolargetime = false;
				var principalRadioTips=true;
				var newDeps = "";
				taskEditor.find("tr[depends]").each(function() {
						var dStr = "";
						var dpAss = $(this);
						var taskIndex = dpAss.find("[name=taskId]").val();
						var type = 1;
						var typeStr ="";
						type = dpAss.find("[name=type]").val();
						var delayDay = dpAss.find("[name=delayDay]").val();
						if(type==0)
							typeStr = "-FF";
						else if(type==2)
							typeStr = "-SS";
						else if(type==3)
							typeStr = "-SF";
							
						if(delayDay==0)
							dStr = taskIndex + typeStr;
						else
							dStr = taskIndex + ":" + delayDay + typeStr;
							
						newDeps = newDeps + dStr +",";
				});
				if(newDeps.length>0)
					newDeps = newDeps.substring(0,newDeps.length-1);
				taskEditor.find("tr[assId]").each(
					function() {
						var trAss = $(this);
						var effort = millisFromString(
								trAss.find("[name=effort]").val(), true);
						var hourEffort = effort / 1000.0 / 3600.0;
						if (hourEffort / lengofDay > 24){
							toolargetime = true;
						}
						var principalRadio = trAss.find("[name=principalRadio]:checked").val();	
						if(principalRadio&&principalRadio=='on'){
							if(trAss.find("[name=resourceId]").val()&&trAss.find("[name=resourceId]").val()!=""){
								resourceId = trAss.find("[name=resourceId]").val();
								principalRadioTips=false;
							}
						}
				});
				
				if (toolargetime) {
					var question = confirm("个人工作量超出了每天24小时限度，请确认是否提交");
					if (question == false)
						return;
				}
				
				var isAssignedCk=taskEditor.find("#isAssigned").is(":checked");

				if(isAssignedCk){
					if (!task.hasChild) {// 父节点
						if (principalRadioTips) {
							alert("请选择任务负责人！");
							return;
						}
					}else{
						if (!taskEditor.find("#principal option:selected").val()||taskEditor.find("#principal option:selected").val()=="") {
							alert("未选择任务负责人");
							return;
						}else{
							resourceId=taskEditor.find("#principal option:selected").val();
						}
					}
				}
				
				// 删除已保存人员
				for ( var i = 0; i < task.assigs.length; i++) {
					var newfound = false;
					var principalRadioDel = false;
					var ass = task.assigs[i];
					taskEditor.find("tr[assId]").each(function() {
						var trAss = $(this);
						//console.dir(trAss.find("[name=resourceId_txt]"));
						if(trAss.find("[name=resourceId_txt]")){
							var assId = trAss.attr("assId");
							//var principalRadio = trAss.find("[name=principalRadio]:checked").val();	
							var resName = trAss.find("[name=resourceId_txt]").val(); 
							var resId = trAss.find("[name=resourceId]").val();
							var roleId = trAss.find("[name=roleId]").val();
							var res = self.master.getAllResource(resId,resName);// 这里要取所有的用户名列表找，因为评审任务
							if (assId == ass.id) {
								newfound = true;
							} else if (roleId == ass.roleId&& res.t == ass.resourceId) {
								newfound = true;
							}
						}
					});
					if(!newfound){
						//delete task.assigs[i];
						 task.assigs.splice(i,1);
					}
				}


				
				self.master.beginTransaction();
				task.principal=resourceId;
				if (task.name != taskEditor.find("#name").val()) {
					if (task.activityId != ""
							|| task.processId != ""
							|| task.isFromTemplate == 1)
						task.master.needReason = true;
				}
				task.name = taskEditor.find("#name").val();
				task.description = taskEditor.find("#description").val();
						
				task.code = taskEditor.find("#code").val();
				task.progress = parseFloat(taskEditor.find(
						"#progress").val());
				// task.duration =
				// parseInt(taskEditor.find("#duration").val());
				// //bicch rimosso perch猫 devono essere ricalcolata
				// dalla start end, altrimenti sbaglia
				task.startIsMilestone = taskEditor.find(
						"#startIsMilestone").is(":checked");
				task.endIsMilestone = taskEditor.find("#endIsMilestone").is(":checked");
						

				task.type = taskEditor.find("#type").find(
						"option:selected").text();
				task.typeId = taskEditor.find("#type").val();
				if (task.typeId == "R" || task.typeId == "Q"
						|| task.typeId == "T")
					task.reportType = task.typeId;
				else
					task.reportType = "";

				task.relevance = taskEditor.find("#relevance")
						.val();
				task.progressByWorklog = taskEditor.find("#progressByWorklog").is(":checked");
						
				//task.principal = taskEditor.find("#principal").val();
						
				task.approver = taskEditor.find("#approver").val();
				task.approverText = taskEditor.find("#approver").find("option:selected").text();
				task.relatedProject = taskEditor.find(
						"#relatedProject").val();
				task.isAssigned = taskEditor.find("#isAssigned")
						.is(":checked");
				task.isMilestone = taskEditor.find("#isMilestone")
						.is(":checked");
				task.isPhase = taskEditor.find("#isPhase").is(
						":checked");
				// set assignments
				var cnt = 0;
				var planWorkLoad = 0.0;
				//console.dir(taskEditor.find("tr[assId]"));

				var newAssigs=[];
				taskEditor.find("tr[assId]").each(
								function() {
									var trAss = $(this);
									var assId = trAss.attr("assId");
									var resId = trAss.find("[name=resourceId]").val();
											
									var resName = trAss.find("[name=resourceId_txt]").val(); 
											
/*												var resName = trAss
												.find(
														"[name=resourceId_txt]")
														.val(); 
*/												
									// from
													// smartcombo
													// text input
													// part
									var roleId = trAss.find("[name=roleId]").val();
											
									var effort = millisFromString(trAss.find("[name=effort]").val(), true);

									//console.dir(trAss.find("[name=effort]").val());
											
									var hourEffort = effort / 1000.0 / 3600.0;
									// check if the selected
									// resource exists in
									// ganttMaster.resources
									var res = self.master.getAllResource(resId,resName);// 这里要取所有的用户名列表找，因为评审任务
		
									// if resource is not found nor
									// created
									if (!res) {
										alert("人员取值问题");
										return;
									}
									

									// check if an existing assig
									// has been deleted and
									// re-created with the same
									// values
									var found = false;
									for ( var i = 0; i < task.assigs.length; i++) {
										var ass = task.assigs[i];

										if (assId == ass.id) {
											ass.effort = effort;
											ass.roleId = roleId;
											ass.resourceId = res.id;
											ass.touched = true;
											planWorkLoad += hourEffort;
											//console.dir(" planWorkLoad += hourEffort"+ planWorkLoad);
											//console.dir(" planWorkLoad += assId"+ assId);
											found = true;
											break;

										} else if (roleId == ass.roleId&& res.t == ass.resourceId) {

											ass.effort = ass.effort+effort;
											ass.touched = true;
											planWorkLoad += hourEffort;
											found = true;
											break;
										}
									}
									var newhourEffortFalg=false;
									if(assId.indexOf("tmp_") == 0&&!found){
										for ( var i = 0; i < task.assigs.length; i++) {
											if(res.id != resourceId&&assId != ass.id){
												newhourEffortFalg=true;
											}
										}
									}
									
									if(task.assigs.length==0){
										planWorkLoad += hourEffort;
									}
									
									
									if(newhourEffortFalg){
										planWorkLoad += hourEffort;
									}
									
									if (!found && resId && roleId) { // insert
										cnt++;
										var ass = task.createAssignment("tmp_"+ new Date().getTime()+ "_"+ cnt,
														resId,
														roleId,
														effort);
										ass.touched = true;
									}

								});
				
				var flag = newCycleTask(taskEditor,task,self,taskId,resourceId,planWorkLoad);//周期性任务
				if(flag){
					return;//用户取消周期性任务的修改 停止
				}
				if (task.getChildren().length == 0) {
					task.planWorkload = planWorkLoad;
				} else {
					var t = 0.0;
					var chd = task.getChildren();
					for ( var i = 0; i < chd.length; i++) {

						t += chd[i].planWorkload;
					}
					task.planWorkload = t;

				}

				// remove untouched assigs
				task.assigs = task.assigs.filter(function(ass) {
					var ret = ass.touched;
					delete ass.touched;
					return ret;
				});

				// 如果任务负责人不在任务成员里，加一条
				/*if (task.principal) {
					var nowAssigs = task.assigs;
					var hasFound = false;
					var nowPrincipal = task.principal;
					var index = 0;
					for (index = 0; index < nowAssigs.length; index++) {
						var asi = nowAssigs[index];
						var resourceIdi = asi.resourceId;
						if (resourceIdi == nowPrincipal) {
							hasFound = true;
						}
					}
					if (!hasFound) {
						var ppass = task.createAssignment("tmp_"
								+ new Date().getTime() + "_" + cnt,
								nowPrincipal, "", 0);
						ppass.touched = true;
					}

				}*/

				// set assignments
				taskEditor
						.find("tr[productId]")
						.each(
								function() {
									var trWp = $(this);
									var productId = trWp
											.attr("productId");
									var productName = trWp.find(
											"[name=productName]")
											.val();
									var parentId = trWp.find(
											"[name=parentId]")
											.val();
									var planSize = trWp.find(
											"[name=planSize]")
											.val();
//									var realSize = trWp.find(
//									"[name=realSize]")
//									.val();
									var sizeUnitStr = trWp.find(
											"[name=sizeUnitStr]")
											.val();
									if (planSize == undefined
											|| planSize == "")
										planSize = 0;
									// check if an existing assig
									// has been deleted and
									// re-created with the same
									// values
									var found = false;
									for ( var i = 0; i < task.workProduct.length; i++) {
										var workProduct = task.workProduct[i];
										if (productId == workProduct.productId) {
											workProduct.planSize = planSize;
											//workProduct.realSize = realSize;
											workProduct.touched = true;
											found = true;
											break;

										}
									}

									if (!found && productId) { // insert
										cnt++;
										var wp = task.createWP(
												productId,
												productName,
												parentId, 
												planSize,
												sizeUnitStr);
										wp.touched = true;

									}

								});

				task.workProduct = task.workProduct
						.filter(function(workProduct) {
							var ret = workProduct.touched;
							delete workProduct.touched;
							return ret;
						});

	        var oldDeps = task.depends;
	        task.depends = newDeps;
	
	        // update links
	        var linkOK = self.master.updateLinks(task);
	        if (linkOK) {
	          self.master.changeTaskDeps(task); //dates recomputation from dependencies
	        }else{
				task.depends = oldDeps;
	        }


				// change dates
				task.setPeriod(Date.parseString(
						taskEditor.find("#start").val()).getTime(),
						Date.parseString(
								taskEditor.find("#end").val())
								.getTime()
								+ (3600000 * 22));

				// change status
				// task.changeStatus(taskEditor.find("#status").val());
				var todoOk = false;
                // 将父任务变更为未发布状态  周期性任务：点击发布后 发布创建的子任务 父任务不发布
				if (task.status == "STATUS_ACTIVE" || task.status == "STATUS_UNDEFINED") {
					if (task.isLoop !=1 && (taskEditor.find("#isAssigned").is(":checked"))) {

						todoOk = task.changeStatus("STATUS_ACTIVE");
						if (todoOk) {
							task.taskStatusValue = 0;
						}
					} else {
						task.isAssigned=false;
						task.changeStatus("STATUS_UNDEFINED");
					}
				}
				task.needRefreshSelect = true;

				if (self.master.endTransaction()) {
					taskEditor.find(":input").updateOldValue();
					//批量发布状态修改
					if(task.canWrite&&!task.hasChild){
						var releaseStatus=$(window.document).find("tr[id=tid_"+task.id+"]").find(".releaseStatus");
						if(task.isAssigned){
							releaseStatus.attr("idChecked", true);
						}else{
							releaseStatus.attr("idChecked", false);
						}
					}
					
					closeBlackPopup();
				}
			});
	//===============================}
		//查询计划变更阶段
		/*if(!queryPlanChangeInfoState(task)){
			taskEditor.find("#isPhase").prop("disabled",true);
		}*/
		
		taskEditor.attr("alertonchange", "true");
		var ndo = createModalPopup(windowWidth, windowHeight).append(taskEditor);// .append("<div
																					// style='height:800px;
																					// background-color:red;'></div>")
	
		// workload computation
		if (typeof (workloadDatesChanged) == "function")
			workloadDatesChanged();
	
		// fxc working
	
		var resEl = taskEditor.find("#principal");
		var opt = $("<option>");
		resEl.append(opt);
		if (task.typeId == "Q") {
	
			//for ( var i = 0; i < task.master.qaOnlyResources.length; i++) {
			for ( var i = 0; i < task.master.qaResources.length; i++) {
				var res = task.master.qaResources[i];
				opt = $("<option>");
				opt.val(res.id).html(res.name);
				if (task.principal == res.id)
					opt.attr("selected", "true");
				resEl.append(opt);
			}
		} else {
	
			for ( var i = 0; i < task.master.resources.length; i++) {
				var res = task.master.resources[i];
				opt = $("<option>");
				opt.val(res.id).html(res.name);
				if (task.principal == res.id)
					opt.attr("selected", "true");
				resEl.append(opt);
			}
		}
	
		var appEl = taskEditor.find("#approver");
		opt = $("<option>");
		appEl.append(opt);
		if (task.typeId == "Q") {
			for ( var i = 0; i < task.master.qaResources.length; i++) {
				var res = task.master.qaResources[i];
				opt = $("<option>");
				opt.val(res.id).html(res.name);
				if (task.approver == res.id)
					opt.attr("selected", "true");
				appEl.append(opt);
			}
		} else {
	
			for ( var i = 0; i < task.master.resources.length; i++) {
				var res = task.master.resources[i];
				opt = $("<option>");
				opt.val(res.id).html(res.name);
				if (task.approver == res.id)
					opt.attr("selected", "true");
				appEl.append(opt);
			}
		}
	
		var typeEl = taskEditor.find("#type");
		for ( var i = 0; i < task.master.types.length; i++) {
			var types = task.master.types[i];
			opt = $("<option>");
			opt.val(types.id).html(types.name);
			if (task.typeId == types.id)
				opt.attr("selected", "true");
			typeEl.append(opt);
		}
		typeEl.focusin(function() {
			oldType = taskEditor.find("#type").val();
		});
		typeEl.change(function() {
			// alert(oldType);
			// alert(taskEditor.find("#type").val() );
			if (taskEditor.find("#type").val() == "Q") {
				var resEl2 = taskEditor.find("#principal");
				resEl2.empty();
				opt = $("<option>");
				resEl2.append(opt);
				//for ( var i = 0; i < task.master.qaOnlyResources.length; i++) {
				for ( var i = 0; i < task.master.qaResources.length; i++) {
					var res = task.master.qaResources[i];
					opt = $("<option>");
					opt.val(res.id).html(res.name);
					if (task.principal == res.id)
						opt.attr("selected", "true");
					resEl2.append(opt);
				}
				var appEl2 = taskEditor.find("#approver");
				appEl2.empty();
				opt = $("<option>");
				appEl2.append(opt);
				for ( var i = 0; i < task.master.qaResources.length; i++) {
					var res = task.master.qaResources[i];
					opt = $("<option>");
					opt.val(res.id).html(res.name);
					if (task.principal == res.id)
						opt.attr("selected", "true");
					appEl2.append(opt);
				}
				$(".delAssig").closest("[assId]").fadeOut(200, function() {
					$(this).remove()
				});
				taskEditor.find("#addAssig").click();
			} else if (taskEditor.find("#type").val() == "R") {
				var resEl2 = taskEditor.find("#principal");
				resEl2.empty();
				opt = $("<option>");
				resEl2.append(opt);
				for ( var i = 0; i < task.master.resources.length; i++) {
					var res = task.master.resources[i];
					opt = $("<option>");
					opt.val(res.id).html(res.name);
					if (task.principal == res.id)
						opt.attr("selected", "true");
					resEl2.append(opt);
				}
				var appEl2 = taskEditor.find("#approver");
				appEl2.empty();
				opt = $("<option>");
				appEl2.append(opt);
				for ( var i = 0; i < task.master.resources.length; i++) {
					var res = task.master.resources[i];
					opt = $("<option>");
					opt.val(res.id).html(res.name);
					if (task.principal == res.id)
						opt.attr("selected", "true");
					appEl2.append(opt);
				}
				$(".delAssig").closest("[assId]").fadeOut(200, function() {
					$(this).remove()
				});
				taskEditor.find("#addAssig").click();
			} else {
				if (oldType == "R") {
					var resEl2 = taskEditor.find("#principal");
					resEl2.empty();
					opt = $("<option>");
					resEl2.append(opt);
					for ( var i = 0; i < task.master.resources.length; i++) {
						var res = task.master.resources[i];
						opt = $("<option>");
						opt.val(res.id).html(res.name);
						if (task.principal == res.id)
							opt.attr("selected", "true");
						resEl2.append(opt);
					}
					var appEl2 = taskEditor.find("#approver");
					appEl2.empty();
					opt = $("<option>");
					appEl2.append(opt);
					for ( var i = 0; i < task.master.resources.length; i++) {
						var res = task.master.resources[i];
						opt = $("<option>");
						opt.val(res.id).html(res.name);
						if (task.principal == res.id)
							opt.attr("selected", "true");
						appEl2.append(opt);
					}
					$(".delAssig").closest("[assId]").fadeOut(200, function() {
						$(this).remove()
					});
					taskEditor.find("#addAssig").click();
				} else if (oldType == "Q") {
					var resEl2 = taskEditor.find("#principal");
					resEl2.empty();
					opt = $("<option>");
					resEl2.append(opt);
					for ( var i = 0; i < task.master.resources.length; i++) {
						var res = task.master.resources[i];
						opt = $("<option>");
						opt.val(res.id).html(res.name);
						if (task.principal == res.id)
							opt.attr("selected", "true");
						resEl2.append(opt);
					}
					var appEl2 = taskEditor.find("#approver");
					appEl2.empty();
					opt = $("<option>");
					appEl2.append(opt);
					for ( var i = 0; i < task.master.resources.length; i++) {
						var res = task.master.resources[i];
						opt = $("<option>");
						opt.val(res.id).html(res.name);
						if (task.principal == res.id)
							opt.attr("selected", "true");
						appEl2.append(opt);
					}
					$(".delAssig").closest("[assId]").fadeOut(200, function() {
						$(this).remove()
					});
					taskEditor.find("#addAssig").click();
				}
			}
		});
		var relatedProjectEl = taskEditor.find("#relatedProject");
		opt = "";
		relatedProjectEl.append(opt);
		for ( var i = 0; i < task.master.relatedProjects.length; i++) {
			var res = task.master.relatedProjects[i];
			opt = $("<option>");
			opt.val(res.id).html(res.name);
			if (task.relatedProject == res.id)
				opt.attr("selected", "true");
	
			relatedProjectEl.append(opt);
		}
	
		if (task.isMilestone)
			taskEditor.find("#isMilestone").prop("checked", true);
	
		if (task.isPhase)
			taskEditor.find("#isPhase").prop("checked", true);
	
		if (task.isAssigned)
			taskEditor.find("#isAssigned").prop("checked", true);
		if (!task.master.canModifyMilestone) {
	
			taskEditor.find("#isMilestone").prop("disabled", true);
		}
		
//		if (!task.master.canModifyIsPhase) {
//			taskEditor.find("#isPhase").prop("disabled", true);
//		}
		//祖先和子孙任务里有阶段任务的时候，本任务不能设置阶段
		var canSetPhase = true;
		var parents = task.getParents();
		if (parents.length > 0)
			for ( var i = 0; i < parents.length; i++) {
				if (parents[i].isPhase) {
					canSetPhase = false;
				}
			}
		var children = task.getChildren();
		var childrenQueue = [];
		for ( var i = 0; i < children.length; i++) {
			childrenQueue.push(children[i]);
		}
		while (childrenQueue.length > 0) {
			var cTask = childrenQueue.shift();
			var cc = cTask.getChildren();
			for ( var i = 0; i < cc.length; i++) {
				childrenQueue.push(cc[i]);
			}
			if (cTask.isPhase) {
				canSetPhase = false;
			}
		}
		if (!canSetPhase) {
			taskEditor.find("#isPhase").prop("disabled", true);
		}
	
		if (task.coordinateEdit) {
			taskEditor.find("#principal").prop("disabled", true);
			taskEditor.find("#type").prop("disabled", true);
		}
			
//	alert(154601);
//	alert($("select.assSelect").length);
		//$("select.assSelect").select2();
		//$("#approver").select2();
	
	}
};

//function changeDepends(obj, dpTable) {
//		var num=0;
//		var taskIdEl = obj;
//		if(taskIdEl.val()!=""){
//			dpTable.find("tr").each(
//					function() {
//						var trD = obj;
//						var tId = trD.find("[name=taskId]").val();	
//						if(taskIdEl.val()==tId){
//							num++;
//						}
//				});
//		}
//		
//		if(taskIdEl.val()!=""&&num>1){
//			alert("已存在相同任务,不可重复添加");
//			taskIdEl.val("");
//		}else{
//			if(taskIdEl.val()!=""){
//				var selectedOp = taskIdEl.find("option:selected").eq(0);
//				dpRow.find("[name=taskName]").eq(0).text(selectedOp.attr("taskName"));
//			}
//		}
//}


function getResourcesName(userId,task){
	var userTxt="";
	  for(var i=0; i< task.master.allResources.length;i++){
		  var res = task.master.allResources[i];
		  if(userId&&userId==res.id){
			  userTxt=res.name;
			  return userTxt;
		  }
	  }
	  return userTxt
	
}

function getRelatedProjectName(relatedProjectId,task){
	var relatedProjectTxt="";
	for ( var i = 0; i < task.master.relatedProjects.length; i++) {
		var res = task.master.relatedProjects[i];
		if (relatedProjectId == res.id){
			relatedProjectTxt=res.name;
			return relatedProjectTxt
		}
	}
	return relatedProjectTxt
	
}

function getTaskDateChangeValue(task,type){
	var parents;
	var futureParents = task.getParents();
	if (futureParents.length > 0){
		for ( var i = 0; i < futureParents.length; i++) {
			if (futureParents[i].id=="tmp_-1") {
				parents=futureParents[i];
			}
		}
	}
	 return  parents;
}

function openWindow(url,windowName){
	if(!windowName){
		windowName = "_blank";
	}
	var height = window.screen.height*0.7;
	var width = window.screen.width*0.7;
	var top = (window.screen.height-height)/2;
	var left = (window.screen.width-width)/2;
	var newWindow = window.open(url,windowName,"width="+width+",height="+height+",top="+top+",left="+left+",toolbar=no,menubar=no,scrollbars=yes,resizable=no,location=no,status=no");
	newWindow.focus();
}
function openNewWindow(url,windowName,widthCoeff,heightCoeff){
	if(!windowName){
		windowName = "_blank";
	}
	//console.dir(widthCoeff);
	//console.dir(heightCoeff);
	var height = window.screen.height*heightCoeff;
	var width = window.screen.width*widthCoeff;
	//console.dir(width);
	//console.dir(height);
	var top = (window.screen.height-height)/2;
	var left = (window.screen.width-width)/2;
	var newWindow = window.open(url,windowName,"width="+width+",height="+height+",top="+top+",left="+left+",toolbar=no,menubar=no,scrollbars=yes,resizable=no,location=no,status=no");
	newWindow.focus();
}
function initFrequency(){
	var html = "";
	for(var i=0;i<12;i++){
		html+='<option value="'+(i+1)+'">'+(i+1)+'</option>';
	}
	return html;
}

//批量发布任务
function batchReleaseTask(task,el,self){
	 if (el.prop("class") == "releaseStatus"&&!(el.attr("isDisabled")==true||el.attr("isDisabled")=="true")){
		 self.master.beginTransaction();
	 	 	if(el.attr("idChecked")=='false'||el.attr("idChecked")==false){//设置发布
	 	 		var releaseFalg=true;
	 	 		//已发布不能重复发布
	 	 		if(task.isAssigned){
	 	 			alert("已发布任务不能重复发布");
	 	 			releaseFalg=false;
	 	 		}else{
	   				if (task.approver.length < 1) {
	   					alert("未选择任务审批人");
	   					releaseFalg=false;
	   				}else{
	   					if (!task.principal||task.principal.length < 1) {
		   					alert("未选择任务负责人");
		   					releaseFalg=false;
		   				}
	   				}
	 	 		}
	 	 		if(releaseFalg){
	 	 			 task.isAssigned =true;
	 	 			el.attr("idChecked", true);
	 	 			if (task.canWrite&&!task.hasChild&&(task.status == "STATUS_ACTIVE"|| task.status == "STATUS_UNDEFINED")) {
						if (task.isAssigned) {
							todoOk = task.changeStatus("STATUS_ACTIVE");
							if ("5"==task.taskStatusValue) {
								task.taskStatusValue = "0";
							}
						} else {
							task.changeStatus("STATUS_UNDEFINED");
							task.taskStatusValue = "5";
						}
					}
	 	 		}else{
	 	 			el.attr("idChecked", false);
	 	 		}
	 	 	}else{
				el.attr("idChecked", false);
				
				task.isAssigned =false;
				
				if (task.canWrite&&!task.hasChild&&(task.status == "STATUS_ACTIVE"|| task.status == "STATUS_UNDEFINED")) {
					if (task.isAssigned) {
						todoOk = task.changeStatus("STATUS_ACTIVE");
						if ("5"==task.taskStatusValue) {
							task.taskStatusValue = "0";
						}
					} else {
						task.changeStatus("STATUS_UNDEFINED");
						task.taskStatusValue = "5";
					}
				}
	 	 	}
	 	 	self.master.endTransaction();
	    }
}

GridEditor.prototype.batchAdjustTaskTimePage = function (task,ProjID) {
	var master = this.master;
	if(master.__undoStack.length < 1){
		openWindow('/pm/GanttAppletNewAction.do?method=batchAdjustTaskTimePage&projectId='+ProjID+'&from=thisPhase&opFlag=create');
	}else {
		alert("已添加新任务，请先保存甘特图");
	}
};